diff --git a/src/api/java/appeng/api/AEApi.java b/src/api/java/appeng/api/AEApi.java index 2772efa27..6185d79a8 100644 --- a/src/api/java/appeng/api/AEApi.java +++ b/src/api/java/appeng/api/AEApi.java @@ -51,17 +51,17 @@ public enum AEApi HELD_API = (IAppEngApi) apiField.get( apiClass ); } - catch ( ClassNotFoundException e ) + catch( ClassNotFoundException e ) { - throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FQN + " class, without it being declared." ); + throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FQN + " class, without it being declared." ); } - catch ( NoSuchFieldException e ) + catch( NoSuchFieldException e ) { throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FIELD + " field in " + CORE_API_FQN + " without it being declared." ); } - catch ( IllegalAccessException e ) + catch( IllegalAccessException e ) { - throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FIELD + " field in " + CORE_API_FQN + " without enough access permissions."); + throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FIELD + " field in " + CORE_API_FQN + " without enough access permissions." ); } } diff --git a/src/api/java/appeng/api/config/AccessRestriction.java b/src/api/java/appeng/api/config/AccessRestriction.java index cd1ae993c..9b7e4bf33 100644 --- a/src/api/java/appeng/api/config/AccessRestriction.java +++ b/src/api/java/appeng/api/config/AccessRestriction.java @@ -30,7 +30,8 @@ public enum AccessRestriction private final int permissionBit; - AccessRestriction( int v ) { + AccessRestriction( int v ) + { this.permissionBit = v; } @@ -44,19 +45,9 @@ public enum AccessRestriction return this.getPermByBit( this.permissionBit & ar.permissionBit ); } - public AccessRestriction addPermissions( AccessRestriction ar ) - { - return this.getPermByBit( this.permissionBit | ar.permissionBit ); - } - - public AccessRestriction removePermissions( AccessRestriction ar ) - { - return this.getPermByBit( this.permissionBit & ( ~ar.permissionBit ) ); - } - private AccessRestriction getPermByBit( int bit ) { - switch ( bit ) + switch( bit ) { default: case 0: @@ -69,4 +60,14 @@ public enum AccessRestriction return READ_WRITE; } } + + public AccessRestriction addPermissions( AccessRestriction ar ) + { + return this.getPermByBit( this.permissionBit | ar.permissionBit ); + } + + public AccessRestriction removePermissions( AccessRestriction ar ) + { + return this.getPermByBit( this.permissionBit & ( ~ar.permissionBit ) ); + } } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/FuzzyMode.java b/src/api/java/appeng/api/config/FuzzyMode.java index 460f56676..f59cb64b3 100644 --- a/src/api/java/appeng/api/config/FuzzyMode.java +++ b/src/api/java/appeng/api/config/FuzzyMode.java @@ -32,7 +32,8 @@ public enum FuzzyMode final public float breakPoint; final public float percentage; - FuzzyMode( float p ) { + FuzzyMode( float p ) + { this.percentage = p; this.breakPoint = p / 100.0f; } diff --git a/src/api/java/appeng/api/config/PowerUnits.java b/src/api/java/appeng/api/config/PowerUnits.java index 88ecd318e..9ba837c24 100644 --- a/src/api/java/appeng/api/config/PowerUnits.java +++ b/src/api/java/appeng/api/config/PowerUnits.java @@ -32,19 +32,19 @@ public enum PowerUnits RF( "gui.appliedenergistics2.units.thermalexpansion" ), // ThermalExpansion - Redstone Flux MK( "gui.appliedenergistics2.units.mekanism" ); // Mekanism - Joules - PowerUnits( String un ) { - this.unlocalizedName = un; - } - + /** + * unlocalized name for the power unit. + */ + final public String unlocalizedName; /** * please do not edit this value, it is set when AE loads its config files. */ public double conversionRatio = 1.0; - /** - * unlocalized name for the power unit. - */ - final public String unlocalizedName; + PowerUnits( String un ) + { + this.unlocalizedName = un; + } /** * do power conversion using AE's conversion rates. diff --git a/src/api/java/appeng/api/config/Settings.java b/src/api/java/appeng/api/config/Settings.java index bfebed1f5..1ebf42770 100644 --- a/src/api/java/appeng/api/config/Settings.java +++ b/src/api/java/appeng/api/config/Settings.java @@ -57,16 +57,16 @@ public enum Settings private final EnumSet values; + Settings( EnumSet set ) + { + if( set == null || set.isEmpty() ) + throw new RuntimeException( "Invalid configuration." ); + this.values = set; + } + public EnumSet getPossibleValues() { return this.values; } - Settings( EnumSet set ) - { - if ( set == null || set.isEmpty() ) - throw new RuntimeException( "Invalid configuration." ); - this.values = set; - } - } diff --git a/src/api/java/appeng/api/config/Upgrades.java b/src/api/java/appeng/api/config/Upgrades.java index 0a585ee7a..07c679b6d 100644 --- a/src/api/java/appeng/api/config/Upgrades.java +++ b/src/api/java/appeng/api/config/Upgrades.java @@ -75,13 +75,13 @@ public enum Upgrades /** * Registers a specific amount of this upgrade into a specific machine * - * @param item machine in which this upgrade can be installed + * @param item machine in which this upgrade can be installed * @param maxSupported amount how many upgrades can be installed */ public void registerItem( IItemDefinition item, int maxSupported ) { final Optional maybeStack = item.maybeStack( 1 ); - for ( ItemStack stack : maybeStack.asSet() ) + for( ItemStack stack : maybeStack.asSet() ) { this.registerItem( stack, maxSupported ); } @@ -90,7 +90,21 @@ public enum Upgrades /** * Registers a specific amount of this upgrade into a specific machine * - * @param item machine in which this upgrade can be installed + * @param stack machine in which this upgrade can be installed + * @param maxSupported amount how many upgrades can be installed + */ + public void registerItem( ItemStack stack, int maxSupported ) + { + if( stack != null ) + { + this.supportedMax.put( stack, maxSupported ); + } + } + + /** + * Registers a specific amount of this upgrade into a specific machine + * + * @param item machine in which this upgrade can be installed * @param maxSupported amount how many upgrades can be installed * * @deprecated use {@link Upgrades#registerItem(IItemDefinition, int)} @@ -98,31 +112,17 @@ public enum Upgrades @Deprecated public void registerItem( AEItemDefinition item, int maxSupported ) { - if ( item != null ) + if( item != null ) { final ItemStack stack = item.stack( 1 ); - if ( stack != null ) + if( stack != null ) { this.registerItem( stack, maxSupported ); } } } - /** - * Registers a specific amount of this upgrade into a specific machine - * - * @param stack machine in which this upgrade can be installed - * @param maxSupported amount how many upgrades can be installed - */ - public void registerItem( ItemStack stack, int maxSupported ) - { - if ( stack != null ) - { - this.supportedMax.put( stack, maxSupported ); - } - } - public int getTier() { return this.tier; diff --git a/src/api/java/appeng/api/definitions/IBlocks.java b/src/api/java/appeng/api/definitions/IBlocks.java index d10ba5d29..0cb1c6d24 100644 --- a/src/api/java/appeng/api/definitions/IBlocks.java +++ b/src/api/java/appeng/api/definitions/IBlocks.java @@ -20,6 +20,7 @@ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + package appeng.api.definitions; diff --git a/src/api/java/appeng/api/definitions/IComparableDefinition.java b/src/api/java/appeng/api/definitions/IComparableDefinition.java index f98d028ed..db1d9b777 100644 --- a/src/api/java/appeng/api/definitions/IComparableDefinition.java +++ b/src/api/java/appeng/api/definitions/IComparableDefinition.java @@ -14,6 +14,7 @@ public interface IComparableDefinition * Compare {@link ItemStack} with this * * @param comparableStack compared item + * * @return true if the item stack is a matching item. */ boolean isSameAs( ItemStack comparableStack ); @@ -22,9 +23,9 @@ public interface IComparableDefinition * Compare Block with world. * * @param world world of block - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block * * @return if the block is placed in the world at the specific location. */ diff --git a/src/api/java/appeng/api/definitions/IDefinitions.java b/src/api/java/appeng/api/definitions/IDefinitions.java index 0f6a30da7..354f8899f 100644 --- a/src/api/java/appeng/api/definitions/IDefinitions.java +++ b/src/api/java/appeng/api/definitions/IDefinitions.java @@ -20,6 +20,7 @@ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + package appeng.api.definitions; diff --git a/src/api/java/appeng/api/definitions/IItemDefinition.java b/src/api/java/appeng/api/definitions/IItemDefinition.java index c1d8e324a..805d58deb 100644 --- a/src/api/java/appeng/api/definitions/IItemDefinition.java +++ b/src/api/java/appeng/api/definitions/IItemDefinition.java @@ -17,5 +17,5 @@ public interface IItemDefinition extends IComparableDefinition /** * @return an {@link ItemStack} with specified quantity of this item. */ - Optional maybeStack(int stackSize); + Optional maybeStack( int stackSize ); } diff --git a/src/api/java/appeng/api/definitions/IItems.java b/src/api/java/appeng/api/definitions/IItems.java index 179cee8e1..5ea20f2ad 100644 --- a/src/api/java/appeng/api/definitions/IItems.java +++ b/src/api/java/appeng/api/definitions/IItems.java @@ -20,6 +20,7 @@ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + package appeng.api.definitions; diff --git a/src/api/java/appeng/api/definitions/IMaterials.java b/src/api/java/appeng/api/definitions/IMaterials.java index dbb0ad645..8a52bfd53 100644 --- a/src/api/java/appeng/api/definitions/IMaterials.java +++ b/src/api/java/appeng/api/definitions/IMaterials.java @@ -20,6 +20,7 @@ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + package appeng.api.definitions; diff --git a/src/api/java/appeng/api/events/LocatableEventAnnounce.java b/src/api/java/appeng/api/events/LocatableEventAnnounce.java index da3496928..2d8a36a02 100644 --- a/src/api/java/appeng/api/events/LocatableEventAnnounce.java +++ b/src/api/java/appeng/api/events/LocatableEventAnnounce.java @@ -31,19 +31,12 @@ import appeng.api.features.ILocatable; /** * Input Event: - * + * * Used to Notify the Location Registry of objects, and their availability. */ public class LocatableEventAnnounce extends Event { - public enum LocatableEvent - { - Register, // Adds the locatable to the registry - Unregister // Removes the locatable from the registry - } - - final public ILocatable target; final public LocatableEvent change; @@ -52,4 +45,10 @@ public class LocatableEventAnnounce extends Event this.target = o; this.change = ev; } + + public enum LocatableEvent + { + Register, // Adds the locatable to the registry + Unregister // Removes the locatable from the registry + } } diff --git a/src/api/java/appeng/api/features/IGrinderEntry.java b/src/api/java/appeng/api/features/IGrinderEntry.java index 4b1df507a..1667f12cc 100644 --- a/src/api/java/appeng/api/features/IGrinderEntry.java +++ b/src/api/java/appeng/api/features/IGrinderEntry.java @@ -54,6 +54,13 @@ public interface IGrinderEntry */ ItemStack getOutput(); + /** + * allows you to change the output. + * + * @param output output item + */ + void setOutput( ItemStack output ); + /** * gets the current output * @@ -68,13 +75,6 @@ public interface IGrinderEntry */ ItemStack getSecondOptionalOutput(); - /** - * allows you to change the output. - * - * @param output output item - */ - void setOutput( ItemStack output ); - /** * stack, and 0.0-1.0 chance that it will be generated. * diff --git a/src/api/java/appeng/api/features/IGrinderRegistry.java b/src/api/java/appeng/api/features/IGrinderRegistry.java index 6b25cfa57..4076df433 100644 --- a/src/api/java/appeng/api/features/IGrinderRegistry.java +++ b/src/api/java/appeng/api/features/IGrinderRegistry.java @@ -45,8 +45,8 @@ public interface IGrinderRegistry /** * add a new recipe the easy way, in → out, how many turns., duplicates will not be added. * - * @param in input - * @param out output + * @param in input + * @param out output * @param turns amount of turns to turn the input into the output */ void addRecipe( ItemStack in, ItemStack out, int turns ); @@ -54,8 +54,8 @@ public interface IGrinderRegistry /** * add a new recipe with optional outputs, duplicates will not be added. * - * @param in input - * @param out output + * @param in input + * @param out output * @param optional optional output * @param chance chance to get the optional output within 0.0 - 1.0 * @param turns amount of turns to turn the input into the outputs @@ -64,11 +64,11 @@ public interface IGrinderRegistry /** * add a new recipe with optional outputs, duplicates will not be added. - * - * @param in input - * @param out output - * @param optional optional output - * @param chance chance to get the optional output within 0.0 - 1.0 + * + * @param in input + * @param out output + * @param optional optional output + * @param chance chance to get the optional output within 0.0 - 1.0 * @param optional2 second optional output * @param chance2 chance to get the second optional output within 0.0 - 1.0 * @param turns amount of turns to turn the input into the outputs diff --git a/src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java b/src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java index c8939174b..47a48e813 100644 --- a/src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java +++ b/src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java @@ -32,8 +32,8 @@ public interface IMatterCannonAmmoRegistry /** * register a new ammo, generally speaking this is based off of atomic weight to make it easier to guess at - * - * @param ammo new ammo + * + * @param ammo new ammo * @param weight atomic weight */ void registerAmmo( ItemStack ammo, double weight ); diff --git a/src/api/java/appeng/api/features/INetworkEncodable.java b/src/api/java/appeng/api/features/INetworkEncodable.java index f7046a02b..b9aa8beae 100644 --- a/src/api/java/appeng/api/features/INetworkEncodable.java +++ b/src/api/java/appeng/api/features/INetworkEncodable.java @@ -41,13 +41,10 @@ public interface INetworkEncodable /** * Encode the wireless frequency via the Controller. - * - * @param item - * the wireless terminal. - * @param encKey - * the wireless encryption key. - * @param name - * null for now. + * + * @param item the wireless terminal. + * @param encKey the wireless encryption key. + * @param name null for now. */ void setEncryptionKey( ItemStack item, String encKey, String name ); } diff --git a/src/api/java/appeng/api/features/IP2PTunnelRegistry.java b/src/api/java/appeng/api/features/IP2PTunnelRegistry.java index 198ad48c1..69e474cdb 100644 --- a/src/api/java/appeng/api/features/IP2PTunnelRegistry.java +++ b/src/api/java/appeng/api/features/IP2PTunnelRegistry.java @@ -38,11 +38,9 @@ public interface IP2PTunnelRegistry /** * Allows third parties to register items from their mod as potential * attunements for AE's P2P Tunnels - * - * @param trigger - * - the item which triggers attunement - * @param type - * - the type of tunnel + * + * @param trigger - the item which triggers attunement + * @param type - the type of tunnel */ void addNewAttunement( ItemStack trigger, TunnelType type ); diff --git a/src/api/java/appeng/api/features/IRecipeHandlerRegistry.java b/src/api/java/appeng/api/features/IRecipeHandlerRegistry.java index 6b2d9f2bf..ef50b809e 100644 --- a/src/api/java/appeng/api/features/IRecipeHandlerRegistry.java +++ b/src/api/java/appeng/api/features/IRecipeHandlerRegistry.java @@ -34,17 +34,17 @@ public interface IRecipeHandlerRegistry /** * Add a new Recipe Handler to the parser. - * + * * MUST BE CALLED IN PRE-INIT - * - * @param name name of crafthandler + * + * @param name name of crafthandler * @param handler class of crafthandler */ void addNewCraftHandler( String name, Class handler ); /** * Add a new resolver to the parser. - * + * * MUST BE CALLED IN PRE-INIT * * @param sir sub item resolver diff --git a/src/api/java/appeng/api/features/IWirelessTermHandler.java b/src/api/java/appeng/api/features/IWirelessTermHandler.java index cb116e85a..eebfceda2 100644 --- a/src/api/java/appeng/api/features/IWirelessTermHandler.java +++ b/src/api/java/appeng/api/features/IWirelessTermHandler.java @@ -45,11 +45,11 @@ public interface IWirelessTermHandler extends INetworkEncodable /** * use an amount of power, in AE units - * - * @param amount - * is in AE units ( 5 per MJ ), if you return false, the item should be dead and return false for - * hasPower - * @param is wireless terminal + * + * @param amount is in AE units ( 5 per MJ ), if you return false, the item should be dead and return false for + * hasPower + * @param is wireless terminal + * * @return true if wireless terminal uses power */ boolean usePower( EntityPlayer player, double amount, ItemStack is ); diff --git a/src/api/java/appeng/api/features/IWorldGen.java b/src/api/java/appeng/api/features/IWorldGen.java index 4f935dfa6..8e5a9c736 100644 --- a/src/api/java/appeng/api/features/IWorldGen.java +++ b/src/api/java/appeng/api/features/IWorldGen.java @@ -31,11 +31,6 @@ import net.minecraft.world.WorldProvider; public interface IWorldGen { - enum WorldGenType - { - CertusQuartz, ChargedCertusQuartz, Meteorites - } - void disableWorldGenForProviderID( WorldGenType type, Class provider ); void enableWorldGenForDimension( WorldGenType type, int dimID ); @@ -43,4 +38,9 @@ public interface IWorldGen void disableWorldGenForDimension( WorldGenType type, int dimID ); boolean isWorldGenEnabled( WorldGenType type, World w ); + + enum WorldGenType + { + CertusQuartz, ChargedCertusQuartz, Meteorites + } } diff --git a/src/api/java/appeng/api/implementations/items/IBiometricCard.java b/src/api/java/appeng/api/implementations/items/IBiometricCard.java index 49962ef01..c37f6d0c9 100644 --- a/src/api/java/appeng/api/implementations/items/IBiometricCard.java +++ b/src/api/java/appeng/api/implementations/items/IBiometricCard.java @@ -66,16 +66,16 @@ public interface IBiometricCard /** * remove a permission from the item stack. - * - * @param itemStack card + * + * @param itemStack card * @param permission to be removed permission */ void removePermission( ItemStack itemStack, SecurityPermissions permission ); /** * add a permission to the item stack. - * - * @param itemStack card + * + * @param itemStack card * @param permission to be added permission */ void addPermission( ItemStack itemStack, SecurityPermissions permission ); diff --git a/src/api/java/appeng/api/implementations/items/IMemoryCard.java b/src/api/java/appeng/api/implementations/items/IMemoryCard.java index 71a096b45..587e005fc 100644 --- a/src/api/java/appeng/api/implementations/items/IMemoryCard.java +++ b/src/api/java/appeng/api/implementations/items/IMemoryCard.java @@ -31,7 +31,7 @@ import net.minecraft.nbt.NBTTagCompound; /** * Memory Card API - * + * * AE's Memory Card Item Class implements this interface. */ public interface IMemoryCard @@ -40,14 +40,12 @@ public interface IMemoryCard /** * Configures the data stored on the memory card, the SettingsName, will be * localized when displayed. - * - * @param is item - * @param SettingsName - * unlocalized string that represents the tile entity. - * @param data - * may contain a String called "tooltip" which is is a - * unlocalized string displayed after the settings name, optional - * but can be used to add details to the card for later. + * + * @param is item + * @param SettingsName unlocalized string that represents the tile entity. + * @param data may contain a String called "tooltip" which is is a + * unlocalized string displayed after the settings name, optional + * but can be used to add details to the card for later. */ void setMemoryCardContents( ItemStack is, String SettingsName, NBTTagCompound data ); @@ -72,11 +70,9 @@ public interface IMemoryCard /** * notify the user of a outcome related to the memory card. - * - * @param player - * that used the card. - * @param msg - * which message to send. + * + * @param player that used the card. + * @param msg which message to send. */ void notifyUser( EntityPlayer player, MemoryCardMessages msg ); } diff --git a/src/api/java/appeng/api/implementations/items/ISpatialStorageCell.java b/src/api/java/appeng/api/implementations/items/ISpatialStorageCell.java index 8bc6d29bc..1c0f89bfc 100644 --- a/src/api/java/appeng/api/implementations/items/ISpatialStorageCell.java +++ b/src/api/java/appeng/api/implementations/items/ISpatialStorageCell.java @@ -88,11 +88,11 @@ public interface ISpatialStorageCell /** * Perform a spatial swap with the contents of the cell, and the world. - * - * @param is spatial storage cell - * @param w world of spatial - * @param min min coord - * @param max max coord + * + * @param is spatial storage cell + * @param w world of spatial + * @param min min coord + * @param max max coord * @param doTransition transition * * @return result of transition diff --git a/src/api/java/appeng/api/implementations/items/IStorageCell.java b/src/api/java/appeng/api/implementations/items/IStorageCell.java index ba2b3fc10..cf4eade58 100644 --- a/src/api/java/appeng/api/implementations/items/IStorageCell.java +++ b/src/api/java/appeng/api/implementations/items/IStorageCell.java @@ -34,10 +34,10 @@ import appeng.api.storage.data.IAEItemStack; * Any item which implements this can be treated as an IMEInventory via * Util.getCell / Util.isCell It automatically handles the internals and NBT * data, which is both nice, and bad for you! - * + * * Good cause it means you don't have to do anything, bad because you have * little to no control over it. - * + * * The standard AE implementation only provides 1-63 Types */ public interface IStorageCell extends ICellWorkbenchItem @@ -76,8 +76,8 @@ public interface IStorageCell extends ICellWorkbenchItem * Allows you to fine tune which items are allowed on a given cell, if you * don't care, just return false; As the handler for this type of cell is * still the default cells, the normal AE black list is also applied. - * - * @param cellItem item + * + * @param cellItem item * @param requestedAddition requested addition * * @return true to preventAdditionOfItem diff --git a/src/api/java/appeng/api/implementations/parts/IPartCable.java b/src/api/java/appeng/api/implementations/parts/IPartCable.java index ac8d4df8b..0e4347aac 100644 --- a/src/api/java/appeng/api/implementations/parts/IPartCable.java +++ b/src/api/java/appeng/api/implementations/parts/IPartCable.java @@ -70,7 +70,7 @@ public interface IPartCable extends IPart, IGridHost /** * Change sides on the cables node. - * + * * Called by AE, do not invoke. * * @param sides sides of cable diff --git a/src/api/java/appeng/api/implementations/tiles/IChestOrDrive.java b/src/api/java/appeng/api/implementations/tiles/IChestOrDrive.java index 89ce5aaff..0be1d0030 100644 --- a/src/api/java/appeng/api/implementations/tiles/IChestOrDrive.java +++ b/src/api/java/appeng/api/implementations/tiles/IChestOrDrive.java @@ -23,10 +23,12 @@ package appeng.api.implementations.tiles; + import appeng.api.networking.IGridHost; import appeng.api.storage.ICellContainer; import appeng.api.util.IOrientable; + public interface IChestOrDrive extends ICellContainer, IGridHost, IOrientable { @@ -45,9 +47,10 @@ public interface IChestOrDrive extends ICellContainer, IGridHost, IOrientable * 3 - red * * @param slot slot index + * * @return status of the slot, one of the above indices. */ - int getCellStatus(int slot); + int getCellStatus( int slot ); /** * @return if the device is online you should check this before providing any other information. @@ -56,8 +59,8 @@ public interface IChestOrDrive extends ICellContainer, IGridHost, IOrientable /** * @param slot slot index + * * @return is the cell currently blinking to show activity. */ - boolean isCellBlinking(int slot); - + boolean isCellBlinking( int slot ); } diff --git a/src/api/java/appeng/api/implementations/tiles/ICraftingMachine.java b/src/api/java/appeng/api/implementations/tiles/ICraftingMachine.java index 360990794..53ca92b2e 100644 --- a/src/api/java/appeng/api/implementations/tiles/ICraftingMachine.java +++ b/src/api/java/appeng/api/implementations/tiles/ICraftingMachine.java @@ -29,19 +29,20 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.networking.crafting.ICraftingPatternDetails; + public interface ICraftingMachine { /** * inserts a crafting plan, and the necessary items into the crafting machine. * - * @param patternDetails details of pattern - * @param table crafting table + * @param patternDetails details of pattern + * @param table crafting table * @param ejectionDirection ejection direction * * @return if it was accepted, all or nothing. */ - boolean pushPattern(ICraftingPatternDetails patternDetails, InventoryCrafting table, ForgeDirection ejectionDirection); + boolean pushPattern( ICraftingPatternDetails patternDetails, InventoryCrafting table, ForgeDirection ejectionDirection ); /** * check if the crafting machine is accepting pushes via pushPattern, if this is false, all calls to push will fail, @@ -50,5 +51,4 @@ public interface ICraftingMachine * @return true, if pushPattern can complete, if its false push will always be false. */ boolean acceptsPlans(); - } diff --git a/src/api/java/appeng/api/implementations/tiles/ICrankable.java b/src/api/java/appeng/api/implementations/tiles/ICrankable.java index bbe4716e5..787ec6d74 100644 --- a/src/api/java/appeng/api/implementations/tiles/ICrankable.java +++ b/src/api/java/appeng/api/implementations/tiles/ICrankable.java @@ -23,8 +23,10 @@ package appeng.api.implementations.tiles; + import net.minecraftforge.common.util.ForgeDirection; + /** * Crank/Crankable API, * @@ -53,6 +55,5 @@ public interface ICrankable /** * @return true if the crank can attach on the given side. */ - boolean canCrankAttach(ForgeDirection directionToCrank); - + boolean canCrankAttach( ForgeDirection directionToCrank ); } diff --git a/src/api/java/appeng/api/integration/IBeeComparison.java b/src/api/java/appeng/api/integration/IBeeComparison.java index a046a90ac..677e82ce6 100644 --- a/src/api/java/appeng/api/integration/IBeeComparison.java +++ b/src/api/java/appeng/api/integration/IBeeComparison.java @@ -23,6 +23,7 @@ package appeng.api.integration; + /** * An interface to get access to the individual settings for AE's Internal Bee * Comparison handler. @@ -39,5 +40,4 @@ public interface IBeeComparison * @return the Forestry IIndividual for this comparison object - cast this to a IIndividual if you want to use it. */ Object getIndividual(); - } \ No newline at end of file diff --git a/src/api/java/appeng/api/movable/IMovableHandler.java b/src/api/java/appeng/api/movable/IMovableHandler.java index 1217f52e8..01c98f7b4 100644 --- a/src/api/java/appeng/api/movable/IMovableHandler.java +++ b/src/api/java/appeng/api/movable/IMovableHandler.java @@ -23,9 +23,11 @@ package appeng.api.movable; + import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; + public interface IMovableHandler { @@ -34,10 +36,11 @@ public interface IMovableHandler * that single entity, you cannot opt out of single entities. * * @param myClass tile entity class - * @param tile tile entity + * @param tile tile entity + * * @return true if it can handle moving */ - boolean canHandle(Class myClass, TileEntity tile); + boolean canHandle( Class myClass, TileEntity tile ); /** * request that the handler move the the tile from its current location to @@ -56,12 +59,11 @@ public interface IMovableHandler * } * * - * @param tile to be moved tile + * @param tile to be moved tile * @param world world of tile - * @param x x coord of tile - * @param y y coord of tile - * @param z z coord of tile + * @param x x coord of tile + * @param y y coord of tile + * @param z z coord of tile */ - void moveTile(TileEntity tile, World world, int x, int y, int z); - + void moveTile( TileEntity tile, World world, int x, int y, int z ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/movable/IMovableRegistry.java b/src/api/java/appeng/api/movable/IMovableRegistry.java index 2b8c0fa58..be11050b5 100644 --- a/src/api/java/appeng/api/movable/IMovableRegistry.java +++ b/src/api/java/appeng/api/movable/IMovableRegistry.java @@ -23,9 +23,11 @@ package appeng.api.movable; + import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; + /** * Used to determine if a tile is marked as movable, a block will be considered movable, if... * @@ -64,7 +66,7 @@ public interface IMovableRegistry * * @param blk block */ - void blacklistBlock(Block blk); + void blacklistBlock( Block blk ); /** * White list your tile entity with the registry. @@ -74,27 +76,28 @@ public interface IMovableRegistry * * If you tile is handled with IMovableHandler or IMovableTile you do not need to white list it. */ - void whiteListTileEntity(Class c); + void whiteListTileEntity( Class c ); /** * @param te to be moved tile entity + * * @return true if the tile has accepted your request to move it */ - boolean askToMove(TileEntity te); + boolean askToMove( TileEntity te ); /** * tells the tile you are done moving it. * * @param te moved tile entity */ - void doneMoving(TileEntity te); + void doneMoving( TileEntity te ); /** * add a new handler movable handler. * * @param handler moving handler */ - void addHandler(IMovableHandler handler); + void addHandler( IMovableHandler handler ); /** * handlers are used to perform movement, this allows you to override AE's internal version. @@ -102,9 +105,10 @@ public interface IMovableRegistry * only valid after askToMove(...) = true * * @param te tile entity + * * @return moving handler of tile entity */ - IMovableHandler getHandler(TileEntity te); + IMovableHandler getHandler( TileEntity te ); /** * @return a copy of the default handler @@ -113,8 +117,8 @@ public interface IMovableRegistry /** * @param blk block + * * @return true if this block is blacklisted */ - boolean isBlacklisted(Block blk); - + boolean isBlacklisted( Block blk ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/networking/IGrid.java b/src/api/java/appeng/api/networking/IGrid.java index 960f279e6..9ddaf7475 100644 --- a/src/api/java/appeng/api/networking/IGrid.java +++ b/src/api/java/appeng/api/networking/IGrid.java @@ -23,9 +23,11 @@ package appeng.api.networking; + import appeng.api.networking.events.MENetworkEvent; import appeng.api.util.IReadOnlyCollection; + /** * Gives you access to Grid based information. * @@ -38,6 +40,7 @@ public interface IGrid * Get Access to various grid modules * * @param iface face + * * @return the IGridCache you requested. */ C getCache( Class iface ); @@ -45,8 +48,8 @@ public interface IGrid /** * Post an event into the network event bus. * - * @param ev - * - event to post + * @param ev - event to post + * * @return returns ev back to original poster */ MENetworkEvent postEvent( MENetworkEvent ev ); @@ -54,8 +57,8 @@ public interface IGrid /** * Post an event into the network event bus, but direct it at a single node. * - * @param ev - * event to post + * @param ev event to post + * * @return returns ev back to original poster */ MENetworkEvent postEventTo( IGridNode node, MENetworkEvent ev ); @@ -72,6 +75,7 @@ public interface IGrid * Get machines on the network. * * @param gridHostClass class of the grid host + * * @return IMachineSet of all nodes belonging to hosts of specified class. */ IMachineSet getMachines( Class gridHostClass ); @@ -90,5 +94,4 @@ public interface IGrid * @return the node considered the pivot point of the grid. */ IGridNode getPivot(); - } diff --git a/src/api/java/appeng/api/networking/IGridBlock.java b/src/api/java/appeng/api/networking/IGridBlock.java index ea0734eea..89bc8c692 100644 --- a/src/api/java/appeng/api/networking/IGridBlock.java +++ b/src/api/java/appeng/api/networking/IGridBlock.java @@ -33,6 +33,7 @@ import appeng.api.parts.IPart; import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; + /** * An Implementation is required to create your node for IGridHost * @@ -79,12 +80,12 @@ public interface IGridBlock /** * Notifies your IGridBlock that changes were made to your connections */ - void onGridNotification(GridNotification notification); + void onGridNotification( GridNotification notification ); /** * Update Blocks network/connection/booting status. grid, * - * @param grid grid + * @param grid grid * @param channelsInUse used channels */ void setNetworkStatus( IGrid grid, int channelsInUse ); diff --git a/src/api/java/appeng/api/networking/IGridCache.java b/src/api/java/appeng/api/networking/IGridCache.java index cb9a7aa9d..142f5e074 100644 --- a/src/api/java/appeng/api/networking/IGridCache.java +++ b/src/api/java/appeng/api/networking/IGridCache.java @@ -23,14 +23,13 @@ package appeng.api.networking; + /** - * * Allows you to create a network wise service, AE2 uses these for providing * item, spatial, and tunnel services. * * Any Class that implements this, should have a public default constructor that * takes a single argument of type IGrid. - * */ public interface IGridCache { @@ -38,7 +37,6 @@ public interface IGridCache /** * Called each tick for the network, allows you to have active network wide * behaviors. - * */ void onUpdateTick(); @@ -50,9 +48,9 @@ public interface IGridCache * information, do it on the next updateTick. * * @param gridNode removed from that grid - * @param machine to be removed machine + * @param machine to be removed machine */ - void removeNode(IGridNode gridNode, IGridHost machine); + void removeNode( IGridNode gridNode, IGridHost machine ); /** * informs you cache that a machine was added to the grid. @@ -62,9 +60,9 @@ public interface IGridCache * information, do it on the next updateTick. * * @param gridNode added to grid node - * @param machine to be added machine + * @param machine to be added machine */ - void addNode(IGridNode gridNode, IGridHost machine); + void addNode( IGridNode gridNode, IGridHost machine ); /** * Called when a grid splits into two grids, AE will call a split as it @@ -73,7 +71,7 @@ public interface IGridCache * * @param destinationStorage storage which receives half of old grid */ - void onSplit(IGridStorage destinationStorage); + void onSplit( IGridStorage destinationStorage ); /** * Called when two grids merge into one, AE will call a join as it @@ -82,13 +80,12 @@ public interface IGridCache * * @param sourceStorage old storage */ - void onJoin(IGridStorage sourceStorage); + void onJoin( IGridStorage sourceStorage ); /** * Called when saving changes, * * @param destinationStorage storage */ - void populateGridStorage(IGridStorage destinationStorage); - + void populateGridStorage( IGridStorage destinationStorage ); } diff --git a/src/api/java/appeng/api/networking/IGridConnection.java b/src/api/java/appeng/api/networking/IGridConnection.java index ba5be0762..6958dedfe 100644 --- a/src/api/java/appeng/api/networking/IGridConnection.java +++ b/src/api/java/appeng/api/networking/IGridConnection.java @@ -23,8 +23,10 @@ package appeng.api.networking; + import net.minecraftforge.common.util.ForgeDirection; + /** * Access to AE's internal grid connections. * @@ -40,17 +42,19 @@ public interface IGridConnection * lets you get the opposing node of the connection by passing your own node. * * @param gridNode current grid node + * * @return the IGridNode which represents the opposite side of the connection. */ - IGridNode getOtherSide(IGridNode gridNode); + IGridNode getOtherSide( IGridNode gridNode ); /** * determine the direction of the connection based on your node. * * @param gridNode current grid node + * * @return the direction of the connection, only valid for in world connections. */ - ForgeDirection getDirection(IGridNode gridNode); + ForgeDirection getDirection( IGridNode gridNode ); /** * by destroying a connection you may create new grids, and trigger un-expected behavior, you should only destroy @@ -77,5 +81,4 @@ public interface IGridConnection * @return how many channels pass over this connections. */ int getUsedChannels(); - } \ No newline at end of file diff --git a/src/api/java/appeng/api/networking/IGridConnectionVisitor.java b/src/api/java/appeng/api/networking/IGridConnectionVisitor.java index 01dbabab4..1842589e0 100644 --- a/src/api/java/appeng/api/networking/IGridConnectionVisitor.java +++ b/src/api/java/appeng/api/networking/IGridConnectionVisitor.java @@ -23,15 +23,14 @@ package appeng.api.networking; + public interface IGridConnectionVisitor extends IGridVisitor { /** * Called for each connection on the network. * - * @param n - * the connection. + * @param n the connection. */ void visitConnection( IGridConnection n ); - } diff --git a/src/api/java/appeng/api/networking/IGridHost.java b/src/api/java/appeng/api/networking/IGridHost.java index e03a9dbff..3fea9285f 100644 --- a/src/api/java/appeng/api/networking/IGridHost.java +++ b/src/api/java/appeng/api/networking/IGridHost.java @@ -30,11 +30,10 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.parts.IPart; import appeng.api.util.AECableType; + /** - * * Implement to create a networked {@link TileEntity} or {@link IPart} must * be implemented for a part, or tile entity to become part of a grid. - * */ public interface IGridHost { @@ -44,11 +43,11 @@ public interface IGridHost * by returning a valid node later and calling updateState, you can join the * Grid when your block is ready. * - * @param dir - * feel free to ignore this, most blocks will use the same node + * @param dir feel free to ignore this, most blocks will use the same node * for every side. + * * @return a new IGridNode, create these with - * AEApi.INSTANCE().createGridNode( MyIGridBlock ) + * AEApi.INSTANCE().createGridNode( MyIGridBlock ) */ IGridNode getGridNode( ForgeDirection dir ); @@ -64,5 +63,4 @@ public interface IGridHost * break this host, its violating security rules, just break your block, or part. */ void securityBreak(); - } diff --git a/src/api/java/appeng/api/networking/IGridNode.java b/src/api/java/appeng/api/networking/IGridNode.java index e477babe7..a95f79c22 100644 --- a/src/api/java/appeng/api/networking/IGridNode.java +++ b/src/api/java/appeng/api/networking/IGridNode.java @@ -33,14 +33,13 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.IAppEngApi; import appeng.api.util.IReadOnlyCollection; + /** - * * Gives you a view into your Nodes connections and information. * * updateState, getGrid, destroy are required to implement a proper IGridHost. * * Don't Implement; Acquire from {@link IAppEngApi}.createGridNode - * */ public interface IGridNode { @@ -51,7 +50,7 @@ public interface IGridNode * * @param visitor visitor */ - void beginVisit(IGridVisitor visitor); + void beginVisit( IGridVisitor visitor ); /** * inform the node that your IGridBlock has changed its internal state, and force the node to update. @@ -61,7 +60,6 @@ public interface IGridNode * * If your entity is not in the world, or if you IGridHost returns a different node for the same side you will * likely crash the game. - * */ void updateState(); @@ -91,7 +89,6 @@ public interface IGridNode World getWorld(); /** - * * @return a set of the connected sides, UNKNOWN represents an invisible connection */ EnumSet getConnectedSides(); @@ -122,23 +119,23 @@ public interface IGridNode * * Important: You must call this before updateState. * - * @param name nbt name + * @param name nbt name * @param nodeData to be loaded data */ - void loadFromNBT(String name, NBTTagCompound nodeData); + void loadFromNBT( String name, NBTTagCompound nodeData ); /** * this should be called for each node you maintain, you can save all your nodes to the same tag with different * names, if you fail to complete the load / save procedure, network state may be lost between game load/saves. * - * @param name nbt name + * @param name nbt name * @param nodeData to be saved data */ - void saveToNBT(String name, NBTTagCompound nodeData); + void saveToNBT( String name, NBTTagCompound nodeData ); /** * @return if the node's channel requirements are currently met, use this for display purposes, use isActive for - * status. + * status. */ boolean meetsChannelRequirements(); @@ -146,9 +143,15 @@ public interface IGridNode * see if this node has a certain flag * * @param flag flags + * * @return true if has flag */ - boolean hasFlag(GridFlags flag); + boolean hasFlag( GridFlags flag ); + + /** + * @return the ownerID this represents the person who placed the node. + */ + int getPlayerID(); /** * tell the node who was responsible for placing it, failure to do this may result in in-compatibility with the @@ -156,11 +159,5 @@ public interface IGridNode * * @param playerID new player id */ - void setPlayerID(int playerID); - - /** - * @return the ownerID this represents the person who placed the node. - */ - int getPlayerID(); - + void setPlayerID( int playerID ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/networking/IGridVisitor.java b/src/api/java/appeng/api/networking/IGridVisitor.java index da8ab013f..41ac4f475 100644 --- a/src/api/java/appeng/api/networking/IGridVisitor.java +++ b/src/api/java/appeng/api/networking/IGridVisitor.java @@ -23,6 +23,7 @@ package appeng.api.networking; + /** * Simple Visitor pattern access to network nodes. */ @@ -34,11 +35,9 @@ public interface IGridVisitor * * By returning false your informing the host to stop visiting nodes beyond the current node. * - * @param n - * the current node. + * @param n the current node. * * @return true to continue visiting nodes beyond this node. */ boolean visitNode( IGridNode n ); - } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingCallback.java b/src/api/java/appeng/api/networking/crafting/ICraftingCallback.java index 618fd79e6..096b72260 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingCallback.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingCallback.java @@ -23,15 +23,14 @@ package appeng.api.networking.crafting; + public interface ICraftingCallback { /** * this call back is synchronized with the world you passed. * - * @param job - * - final job + * @param job - final job */ void calculationComplete( ICraftingJob job ); - } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingGrid.java b/src/api/java/appeng/api/networking/crafting/ICraftingGrid.java index d5a943206..74fec564a 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingGrid.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingGrid.java @@ -36,57 +36,52 @@ import appeng.api.networking.IGridCache; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEItemStack; + public interface ICraftingGrid extends IGridCache { /** * @param whatToCraft requested craft - * @param world crafting world - * @param slot slot index - * @param details pattern details + * @param world crafting world + * @param slot slot index + * @param details pattern details + * * @return a collection of crafting patterns for the item in question. */ - ImmutableCollection getCraftingFor(IAEItemStack whatToCraft, ICraftingPatternDetails details, int slot, World world); + ImmutableCollection getCraftingFor( IAEItemStack whatToCraft, ICraftingPatternDetails details, int slot, World world ); /** * Begin calculating a crafting job. * - * @param world crafting world - * @param grid network + * @param world crafting world + * @param grid network * @param actionSrc source * @param craftWhat result - * @param callback callback - * -- optional + * @param callback callback + * -- optional * * @return a future which will at an undetermined point in the future get you the {@link ICraftingJob} do not wait - * on this, your be waiting forever. + * on this, your be waiting forever. */ - Future beginCraftingJob(World world, IGrid grid, BaseActionSource actionSrc, IAEItemStack craftWhat, ICraftingCallback callback); + Future beginCraftingJob( World world, IGrid grid, BaseActionSource actionSrc, IAEItemStack craftWhat, ICraftingCallback callback ); /** * Submit the job to the Crafting system for processing. * - * @param job - * - the crafting job from beginCraftingJob - * @param requestingMachine - * - a machine if its being requested via automation, may be null. - * @param target - * - can be null - * - * @param prioritizePower - * - if cpu is null, this determine if the system should prioritize power, or if it should find the lower - * end cpus, automatic processes generally should pick lower end cpus. - * - * @param src - * - the action source to use when starting the job, this will be used for extracting items, should - * usually be the same as the one provided to beginCraftingJob. + * @param job - the crafting job from beginCraftingJob + * @param requestingMachine - a machine if its being requested via automation, may be null. + * @param target - can be null + * @param prioritizePower - if cpu is null, this determine if the system should prioritize power, or if it should find the lower + * end cpus, automatic processes generally should pick lower end cpus. + * @param src - the action source to use when starting the job, this will be used for extracting items, should + * usually be the same as the one provided to beginCraftingJob. * * @return null ( if failed ) or an {@link ICraftingLink} other wise, if you send requestingMachine you need to - * properly keep track of this and handle the nbt saving and loading of the object as well as the - * {@link ICraftingRequester} methods. if you send null, this object should be discarded after verifying the - * return state. + * properly keep track of this and handle the nbt saving and loading of the object as well as the + * {@link ICraftingRequester} methods. if you send null, this object should be discarded after verifying the + * return state. */ - ICraftingLink submitJob(ICraftingJob job, ICraftingRequester requestingMachine, ICraftingCPU target, boolean prioritizePower, BaseActionSource src); + ICraftingLink submitJob( ICraftingJob job, ICraftingRequester requestingMachine, ICraftingCPU target, boolean prioritizePower, BaseActionSource src ); /** * @return list of all the crafting cpus on the grid @@ -95,16 +90,17 @@ public interface ICraftingGrid extends IGridCache /** * @param what to be requested item + * * @return true if the item can be requested via a crafting emitter. */ - boolean canEmitFor(IAEItemStack what); + boolean canEmitFor( IAEItemStack what ); /** * is this item being crafted? * * @param aeStackInSlot item being crafted + * * @return true if it is being crafting */ - boolean isRequesting(IAEItemStack aeStackInSlot); - + boolean isRequesting( IAEItemStack aeStackInSlot ); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingPatternDetails.java b/src/api/java/appeng/api/networking/crafting/ICraftingPatternDetails.java index e66625869..7a4b24199 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingPatternDetails.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingPatternDetails.java @@ -31,6 +31,7 @@ import net.minecraft.world.World; import appeng.api.implementations.ICraftingPatternItem; import appeng.api.storage.data.IAEItemStack; + /** * do not implement provided by {@link ICraftingPatternItem} * @@ -47,11 +48,11 @@ public interface ICraftingPatternDetails /** * @param slotIndex specific slot index * @param itemStack item in slot - * @param world crafting world + * @param world crafting world * * @return if an item can be used in the specific slot for this pattern. */ - boolean isValidItemForSlot(int slotIndex, ItemStack itemStack, World world); + boolean isValidItemForSlot( int slotIndex, ItemStack itemStack, World world ); /** * @return if this pattern is a crafting pattern ( work bench ) @@ -87,17 +88,11 @@ public interface ICraftingPatternDetails * Allow using this INSTANCE of the pattern details to preform the crafting action with performance enhancements. * * @param craftingInv inventory - * @param world crafting world + * @param world crafting world + * * @return the crafted ( work bench ) item. */ - ItemStack getOutput(InventoryCrafting craftingInv, World world); - - /** - * Set the priority the of this pattern. - * - * @param priority priority of pattern - */ - void setPriority(int priority); + ItemStack getOutput( InventoryCrafting craftingInv, World world ); /** * Get the priority of this pattern @@ -105,4 +100,11 @@ public interface ICraftingPatternDetails * @return the priority of this pattern */ int getPriority(); + + /** + * Set the priority the of this pattern. + * + * @param priority priority of pattern + */ + void setPriority( int priority ); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingRequester.java b/src/api/java/appeng/api/networking/crafting/ICraftingRequester.java index 3665ca14e..171ff348a 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingRequester.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingRequester.java @@ -30,6 +30,7 @@ import appeng.api.config.Actionable; import appeng.api.networking.security.IActionHost; import appeng.api.storage.data.IAEItemStack; + public interface ICraftingRequester extends IActionHost { @@ -46,16 +47,16 @@ public interface ICraftingRequester extends IActionHost * be returned. * * @param items item - * @param mode action mode + * @param mode action mode + * * @return unwanted item */ - IAEItemStack injectCraftedItems(ICraftingLink link, IAEItemStack items, Actionable mode); + IAEItemStack injectCraftedItems( ICraftingLink link, IAEItemStack items, Actionable mode ); /** * called when the job changes from in progress, to either complete, or canceled. * * after this call the crafting link is "dead" and should be discarded. */ - void jobStateChange(ICraftingLink link); - + void jobStateChange( ICraftingLink link ); } diff --git a/src/api/java/appeng/api/networking/energy/IAEPowerStorage.java b/src/api/java/appeng/api/networking/energy/IAEPowerStorage.java index 21f2870b2..938c61ce5 100644 --- a/src/api/java/appeng/api/networking/energy/IAEPowerStorage.java +++ b/src/api/java/appeng/api/networking/energy/IAEPowerStorage.java @@ -23,9 +23,11 @@ package appeng.api.networking.energy; + import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; + /** * Used to access information about AE's various power accepting blocks for monitoring purposes. */ @@ -35,7 +37,7 @@ public interface IAEPowerStorage extends IEnergySource /** * Inject amt, power into the device, it will store what it can, and return the amount unable to be stored. * - * @param amt to be injected amount + * @param amt to be injected amount * @param mode action mode * * @return amount of power which was unable to be stored @@ -66,5 +68,4 @@ public interface IAEPowerStorage extends IEnergySource * @return access restriction what the network can do */ AccessRestriction getPowerFlow(); - } \ No newline at end of file diff --git a/src/api/java/appeng/api/networking/energy/IEnergyGrid.java b/src/api/java/appeng/api/networking/energy/IEnergyGrid.java index 449bdfd4f..fe6483a9e 100644 --- a/src/api/java/appeng/api/networking/energy/IEnergyGrid.java +++ b/src/api/java/appeng/api/networking/energy/IEnergyGrid.java @@ -23,10 +23,12 @@ package appeng.api.networking.energy; + import appeng.api.config.Actionable; import appeng.api.networking.IGridCache; import appeng.api.networking.events.MENetworkPowerStatusChange; + /** * AE's Power system. */ @@ -40,7 +42,7 @@ public interface IEnergyGrid extends IGridCache, IEnergySource, IEnergyGridProvi /** * @return the average power drain over the past 10 ticks, includes idle usage during this time, and all use of - * extractPower. + * extractPower. */ double getAvgPowerUsage(); @@ -72,10 +74,9 @@ public interface IEnergyGrid extends IGridCache, IEnergySource, IEnergyGridProvi * Another important note, is that if a network that had overflow is deleted, its power is gone, this is one of the * reasons why keeping overflow to a minimum is important. * - * @param amt - * power to inject into the network - * @param mode - * should the action be simulated or performed? + * @param amt power to inject into the network + * @param mode should the action be simulated or performed? + * * @return the amount of power that the network has OVER the limit. */ double injectPower( double amt, Actionable mode ); @@ -101,5 +102,4 @@ public interface IEnergyGrid extends IGridCache, IEnergySource, IEnergyGridProvi * @return Amount of power required to charge the grid, in AE. */ double getEnergyDemand( double maxRequired ); - } diff --git a/src/api/java/appeng/api/networking/energy/IEnergySource.java b/src/api/java/appeng/api/networking/energy/IEnergySource.java index 4b2917f54..b1b8ac85e 100644 --- a/src/api/java/appeng/api/networking/energy/IEnergySource.java +++ b/src/api/java/appeng/api/networking/energy/IEnergySource.java @@ -23,19 +23,21 @@ package appeng.api.networking.energy; + import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; + public interface IEnergySource { /** * Extract power from the network. * - * @param amt extracted power + * @param amt extracted power * @param mode should the action be simulated or performed? + * * @return returns extracted power. */ double extractAEPower( double amt, Actionable mode, PowerMultiplier usePowerMultiplier ); - } diff --git a/src/api/java/appeng/api/networking/events/MENetworkBootingStatusChange.java b/src/api/java/appeng/api/networking/events/MENetworkBootingStatusChange.java index 3ff180753..febd98024 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkBootingStatusChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkBootingStatusChange.java @@ -23,8 +23,10 @@ package appeng.api.networking.events; + import appeng.api.networking.IGridNode; + /** * Posted by the network when the booting status of the network goes up * or down, the change is reflected via {@link IGridNode}.isActive() diff --git a/src/api/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java b/src/api/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java index db6888b64..42cb405f0 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java +++ b/src/api/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java @@ -23,6 +23,7 @@ package appeng.api.networking.events; + /** * Posted by storage devices to inform AE to refresh its storage structure. * diff --git a/src/api/java/appeng/api/networking/events/MENetworkChannelsChanged.java b/src/api/java/appeng/api/networking/events/MENetworkChannelsChanged.java index 0c430f079..cb2566f44 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkChannelsChanged.java +++ b/src/api/java/appeng/api/networking/events/MENetworkChannelsChanged.java @@ -23,8 +23,10 @@ package appeng.api.networking.events; + import appeng.api.networking.IGridHost; + /** * Posted to the {@link IGridHost} when the channels on the node connections are altered. * diff --git a/src/api/java/appeng/api/networking/events/MENetworkEvent.java b/src/api/java/appeng/api/networking/events/MENetworkEvent.java index b7ff0fd98..638f63326 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkEvent.java +++ b/src/api/java/appeng/api/networking/events/MENetworkEvent.java @@ -23,8 +23,10 @@ package appeng.api.networking.events; + import appeng.api.networking.IGrid; + /** * Part of AE's Event Bus. * @@ -69,7 +71,7 @@ public class MENetworkEvent * * @param v current number of visitors */ - public void setVisitedObjects(int v) + public void setVisitedObjects( int v ) { this.visited = v; } diff --git a/src/api/java/appeng/api/networking/events/MENetworkPowerIdleChange.java b/src/api/java/appeng/api/networking/events/MENetworkPowerIdleChange.java index 9082abd9a..5af71e2c2 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkPowerIdleChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkPowerIdleChange.java @@ -23,8 +23,10 @@ package appeng.api.networking.events; + import appeng.api.networking.IGridNode; + /** * Implementers of a IGridBlock must post this event when your getIdlePowerUsage * starts returning a new value, if you do not post this event the network will @@ -37,8 +39,8 @@ public class MENetworkPowerIdleChange extends MENetworkEvent public final IGridNode node; - public MENetworkPowerIdleChange(IGridNode nodeThatChanged) { + public MENetworkPowerIdleChange( IGridNode nodeThatChanged ) + { this.node = nodeThatChanged; } - } diff --git a/src/api/java/appeng/api/networking/events/MENetworkPowerStatusChange.java b/src/api/java/appeng/api/networking/events/MENetworkPowerStatusChange.java index 272f54c40..ed7ed4bc4 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkPowerStatusChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkPowerStatusChange.java @@ -23,9 +23,11 @@ package appeng.api.networking.events; + import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergyGrid; + /** * Posted by the network when the power status of the network goes up or down, * the change is reflected via the {@link IEnergyGrid}.isNetworkPowered() or via diff --git a/src/api/java/appeng/api/networking/events/MENetworkPowerStorage.java b/src/api/java/appeng/api/networking/events/MENetworkPowerStorage.java index da3445ce8..932a05bff 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkPowerStorage.java +++ b/src/api/java/appeng/api/networking/events/MENetworkPowerStorage.java @@ -23,8 +23,10 @@ package appeng.api.networking.events; + import appeng.api.networking.energy.IAEPowerStorage; + /** * informs the network, that a {@link IAEPowerStorage} block that had either run, * out of power, or was full, is no longer in that state. @@ -37,6 +39,15 @@ import appeng.api.networking.energy.IAEPowerStorage; public class MENetworkPowerStorage extends MENetworkEvent { + public final IAEPowerStorage storage; + public final PowerEventType type; + + public MENetworkPowerStorage( IAEPowerStorage t, PowerEventType y ) + { + this.storage = t; + this.type = y; + } + public enum PowerEventType { /** @@ -49,13 +60,4 @@ public class MENetworkPowerStorage extends MENetworkEvent */ PROVIDE_POWER } - - public final IAEPowerStorage storage; - public final PowerEventType type; - - public MENetworkPowerStorage(IAEPowerStorage t, PowerEventType y) { - this.storage = t; - this.type = y; - } - } diff --git a/src/api/java/appeng/api/networking/events/MENetworkSpatialEvent.java b/src/api/java/appeng/api/networking/events/MENetworkSpatialEvent.java index d02a6c2d7..82a2a7baa 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkSpatialEvent.java +++ b/src/api/java/appeng/api/networking/events/MENetworkSpatialEvent.java @@ -20,6 +20,7 @@ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + package appeng.api.networking.events; diff --git a/src/api/java/appeng/api/networking/events/MENetworkStorageEvent.java b/src/api/java/appeng/api/networking/events/MENetworkStorageEvent.java index 82568685e..e83fa826e 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkStorageEvent.java +++ b/src/api/java/appeng/api/networking/events/MENetworkStorageEvent.java @@ -23,9 +23,11 @@ package appeng.api.networking.events; + import appeng.api.storage.IMEMonitor; import appeng.api.storage.StorageChannel; + /** * posted by the network when the networks Storage Changes, you can use the currentItems list to check levels, and * update status. @@ -40,9 +42,9 @@ public class MENetworkStorageEvent extends MENetworkEvent public final IMEMonitor monitor; public final StorageChannel channel; - public MENetworkStorageEvent(IMEMonitor o, StorageChannel chan) { + public MENetworkStorageEvent( IMEMonitor o, StorageChannel chan ) + { this.monitor = o; this.channel = chan; } - } diff --git a/src/api/java/appeng/api/networking/security/ISecurityGrid.java b/src/api/java/appeng/api/networking/security/ISecurityGrid.java index ad592e75e..3a54590c4 100644 --- a/src/api/java/appeng/api/networking/security/ISecurityGrid.java +++ b/src/api/java/appeng/api/networking/security/ISecurityGrid.java @@ -29,6 +29,7 @@ import net.minecraft.entity.player.EntityPlayer; import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGridCache; + public interface ISecurityGrid extends IGridCache { @@ -41,25 +42,24 @@ public interface ISecurityGrid extends IGridCache * Check if a player has permissions. * * @param player to be checked player - * @param perm checked permissions + * @param perm checked permissions * * @return true if the player has permissions. */ - boolean hasPermission(EntityPlayer player, SecurityPermissions perm); + boolean hasPermission( EntityPlayer player, SecurityPermissions perm ); /** * Check if a player has permissions. * * @param playerID id of player - * @param perm checked permissions + * @param perm checked permissions * * @return true if the player has permissions. */ - boolean hasPermission(int playerID, SecurityPermissions perm); + boolean hasPermission( int playerID, SecurityPermissions perm ); /** * @return PlayerID of the admin, or owner, this is the person who placed the security block. */ int getOwner(); - } diff --git a/src/api/java/appeng/api/networking/security/ISecurityRegistry.java b/src/api/java/appeng/api/networking/security/ISecurityRegistry.java index 92a189735..a2e9ef376 100644 --- a/src/api/java/appeng/api/networking/security/ISecurityRegistry.java +++ b/src/api/java/appeng/api/networking/security/ISecurityRegistry.java @@ -28,6 +28,7 @@ import java.util.EnumSet; import appeng.api.config.SecurityPermissions; + /** * Used by vanilla Security Terminal to post biometric data into the security cache. */ @@ -37,9 +38,8 @@ public interface ISecurityRegistry /** * Submit Permissions into the register. * - * @param PlayerID player id + * @param PlayerID player id * @param permissions permissions of player */ - void addPlayer(int PlayerID, EnumSet permissions); - + void addPlayer( int PlayerID, EnumSet permissions ); } diff --git a/src/api/java/appeng/api/networking/security/MachineSource.java b/src/api/java/appeng/api/networking/security/MachineSource.java index e781a413a..a01b5474b 100644 --- a/src/api/java/appeng/api/networking/security/MachineSource.java +++ b/src/api/java/appeng/api/networking/security/MachineSource.java @@ -29,14 +29,14 @@ public class MachineSource extends BaseActionSource public final IActionHost via; + public MachineSource( IActionHost v ) + { + this.via = v; + } + @Override public boolean isMachine() { return true; } - - public MachineSource( IActionHost v ) - { - this.via = v; - } } diff --git a/src/api/java/appeng/api/networking/security/PlayerSource.java b/src/api/java/appeng/api/networking/security/PlayerSource.java index 66c7c056d..49442bc1b 100644 --- a/src/api/java/appeng/api/networking/security/PlayerSource.java +++ b/src/api/java/appeng/api/networking/security/PlayerSource.java @@ -33,15 +33,15 @@ public class PlayerSource extends BaseActionSource public final EntityPlayer player; public final IActionHost via; - @Override - public boolean isPlayer() - { - return true; - } - public PlayerSource( EntityPlayer p, IActionHost v ) { this.player = p; this.via = v; } + + @Override + public boolean isPlayer() + { + return true; + } } diff --git a/src/api/java/appeng/api/networking/storage/IStackWatcherHost.java b/src/api/java/appeng/api/networking/storage/IStackWatcherHost.java index d460008a1..f2a9f3dcd 100644 --- a/src/api/java/appeng/api/networking/storage/IStackWatcherHost.java +++ b/src/api/java/appeng/api/networking/storage/IStackWatcherHost.java @@ -23,11 +23,13 @@ package appeng.api.networking.storage; + import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; + public interface IStackWatcherHost { @@ -37,17 +39,16 @@ public interface IStackWatcherHost * * @param newWatcher stack watcher */ - void updateWatcher(IStackWatcher newWatcher); + void updateWatcher( IStackWatcher newWatcher ); /** * Called when a watched item changes amounts. * - * @param o changed item list + * @param o changed item list * @param fullStack old stack * @param diffStack new stack - * @param src action source - * @param chan storage channel + * @param src action source + * @param chan storage channel */ - void onStackChange(IItemList o, IAEStack fullStack, IAEStack diffStack, BaseActionSource src, StorageChannel chan); - + void onStackChange( IItemList o, IAEStack fullStack, IAEStack diffStack, BaseActionSource src, StorageChannel chan ); } diff --git a/src/api/java/appeng/api/networking/storage/IStorageGrid.java b/src/api/java/appeng/api/networking/storage/IStorageGrid.java index db3da6ea0..31e8277f0 100644 --- a/src/api/java/appeng/api/networking/storage/IStorageGrid.java +++ b/src/api/java/appeng/api/networking/storage/IStorageGrid.java @@ -23,6 +23,7 @@ package appeng.api.networking.storage; + import appeng.api.networking.IGridCache; import appeng.api.networking.IGridHost; import appeng.api.networking.security.BaseActionSource; @@ -32,6 +33,7 @@ import appeng.api.storage.IStorageMonitorable; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; + /** * Common base class for item / fluid storage caches. */ @@ -48,7 +50,7 @@ public interface IStorageGrid extends IGridCache, IStorageMonitorable * * @param input injected items */ - void postAlterationOfStoredItems(StorageChannel chan, Iterable input, BaseActionSource src); + void postAlterationOfStoredItems( StorageChannel chan, Iterable input, BaseActionSource src ); /** * Used to add a cell provider to the storage system @@ -58,11 +60,10 @@ public interface IStorageGrid extends IGridCache, IStorageMonitorable * * @param cc to be added cell provider */ - void registerCellProvider(ICellProvider cc); + void registerCellProvider( ICellProvider cc ); /** * remove a provider added with addCellContainer */ - void unregisterCellProvider(ICellProvider cc); - + void unregisterCellProvider( ICellProvider cc ); } diff --git a/src/api/java/appeng/api/networking/ticking/IGridTickable.java b/src/api/java/appeng/api/networking/ticking/IGridTickable.java index b655097d3..5e2bd2a50 100644 --- a/src/api/java/appeng/api/networking/ticking/IGridTickable.java +++ b/src/api/java/appeng/api/networking/ticking/IGridTickable.java @@ -23,8 +23,10 @@ package appeng.api.networking.ticking; + import appeng.api.networking.IGridNode; + /** * Implement on IGridHosts which want to use AE's Network Ticking Feature. */ @@ -53,9 +55,8 @@ public interface IGridTickable * reset it. * * @return null or a valid new TickingRequest - * */ - TickingRequest getTickingRequest(IGridNode node); + TickingRequest getTickingRequest( IGridNode node ); /** * AE lets you adjust your tick rate based on the results of your tick, if @@ -66,14 +67,11 @@ public interface IGridTickable * * Note: this is never called if you return null from getTickingRequest. * - * @param TicksSinceLastCall - * the number of world ticks that were skipped since your last - * tick, you can use this to adjust speed of processing or adjust - * your tick rate. + * @param TicksSinceLastCall the number of world ticks that were skipped since your last + * tick, you can use this to adjust speed of processing or adjust + * your tick rate. * * @return tick rate adjustment. - * */ - TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall); - + TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ); } diff --git a/src/api/java/appeng/api/networking/ticking/ITickManager.java b/src/api/java/appeng/api/networking/ticking/ITickManager.java index cda6a71eb..6c5d7de82 100644 --- a/src/api/java/appeng/api/networking/ticking/ITickManager.java +++ b/src/api/java/appeng/api/networking/ticking/ITickManager.java @@ -23,13 +23,13 @@ package appeng.api.networking.ticking; + import appeng.api.networking.IGridCache; import appeng.api.networking.IGridNode; + /** - * * The network tick manager. - * */ public interface ITickManager extends IGridCache { @@ -42,26 +42,23 @@ public interface ITickManager extends IGridCache * * @param node gridnode */ - boolean alertDevice(IGridNode node); + boolean alertDevice( IGridNode node ); /** - * * disables ticking for your device. * * @param node gridnode * * @return if the call was successful. */ - boolean sleepDevice(IGridNode node); + boolean sleepDevice( IGridNode node ); /** - * * enables ticking for your device, undoes a sleepDevice call. * * @param node gridnode * * @return if the call was successful. */ - boolean wakeDevice(IGridNode node); - + boolean wakeDevice( IGridNode node ); } diff --git a/src/api/java/appeng/api/networking/ticking/TickingRequest.java b/src/api/java/appeng/api/networking/ticking/TickingRequest.java index 6d1c71451..6a94f2528 100644 --- a/src/api/java/appeng/api/networking/ticking/TickingRequest.java +++ b/src/api/java/appeng/api/networking/ticking/TickingRequest.java @@ -23,10 +23,9 @@ package appeng.api.networking.ticking; + /** - * * Describes how your tiles ticking is executed. - * */ public class TickingRequest { @@ -37,7 +36,6 @@ public class TickingRequest * Valid Values are : 1+ * * Suggested is 5-20 - * */ public final int minTickRate; @@ -48,30 +46,25 @@ public class TickingRequest * Valid Values are 1+ * * Suggested is 20-40 - * */ public final int maxTickRate; /** - * * Determines the current expected state of your node, if your node expects * to be sleeping, then return true. - * */ public final boolean isSleeping; /** - * * True only if you call {@link ITickManager}.alertDevice( IGridNode ); - * */ public final boolean canBeAlerted; - public TickingRequest(int min, int max, boolean sleep, boolean alertable) { + public TickingRequest( int min, int max, boolean sleep, boolean alertable ) + { this.minTickRate = min; this.maxTickRate = max; this.isSleeping = sleep; this.canBeAlerted = alertable; } - } diff --git a/src/api/java/appeng/api/parts/CableRenderMode.java b/src/api/java/appeng/api/parts/CableRenderMode.java index e3505d999..abe5e7070 100644 --- a/src/api/java/appeng/api/parts/CableRenderMode.java +++ b/src/api/java/appeng/api/parts/CableRenderMode.java @@ -33,7 +33,7 @@ public enum CableRenderMode public final boolean transparentFacades; public final boolean opaqueFacades; - CableRenderMode( boolean hideFacades ) + CableRenderMode( boolean hideFacades ) { this.transparentFacades = hideFacades; this.opaqueFacades = !hideFacades; diff --git a/src/api/java/appeng/api/parts/IFacadeContainer.java b/src/api/java/appeng/api/parts/IFacadeContainer.java index 27fe0e15e..386e5f7b9 100644 --- a/src/api/java/appeng/api/parts/IFacadeContainer.java +++ b/src/api/java/appeng/api/parts/IFacadeContainer.java @@ -31,6 +31,7 @@ import io.netty.buffer.ByteBuf; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; + /** * Used Internally. * @@ -44,17 +45,17 @@ public interface IFacadeContainer * * @return true if the facade as successfully added. */ - boolean addFacade(IFacadePart a); + boolean addFacade( IFacadePart a ); /** * Removed the facade on the given side, or does nothing. */ - void removeFacade(IPartHost host, ForgeDirection side); + void removeFacade( IPartHost host, ForgeDirection side ); /** * @return the {@link IFacadePart} for a given side, or null. */ - IFacadePart getFacade(ForgeDirection s); + IFacadePart getFacade( ForgeDirection s ); /** * rotate the facades left. @@ -66,35 +67,37 @@ public interface IFacadeContainer * * @param data to be written data */ - void writeToNBT(NBTTagCompound data); + void writeToNBT( NBTTagCompound data ); /** * read from stream * * @param data to be read data + * * @return true if it was readable + * * @throws IOException */ - boolean readFromStream(ByteBuf data) throws IOException; + boolean readFromStream( ByteBuf data ) throws IOException; /** * read from NBT * * @param data to be read data */ - void readFromNBT(NBTTagCompound data); + void readFromNBT( NBTTagCompound data ); /** * write to stream * * @param data to be written data + * * @throws IOException */ - void writeToStream(ByteBuf data) throws IOException; + void writeToStream( ByteBuf data ) throws IOException; /** * @return true if there are no facades. */ boolean isEmpty(); - } diff --git a/src/api/java/appeng/api/parts/IFacadePart.java b/src/api/java/appeng/api/parts/IFacadePart.java index bdab0cf21..9d70b6aa3 100644 --- a/src/api/java/appeng/api/parts/IFacadePart.java +++ b/src/api/java/appeng/api/parts/IFacadePart.java @@ -34,6 +34,7 @@ import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + /** * Used Internally. * @@ -51,24 +52,24 @@ public interface IFacadePart * used to collide, and pick the part * * @param ch collision helper - * @param e colliding entity + * @param e colliding entity */ - void getBoxes(IPartCollisionHelper ch, Entity e); + void getBoxes( IPartCollisionHelper ch, Entity e ); /** * render the part. * - * @param x x pos of part - * @param y y pos of part - * @param z z pos of part - * @param instance render helper - * @param renderer renderer - * @param fc face container - * @param busBounds bounding box + * @param x x pos of part + * @param y y pos of part + * @param z z pos of part + * @param instance render helper + * @param renderer renderer + * @param fc face container + * @param busBounds bounding box * @param renderStilt if to render stilt */ - @SideOnly(Side.CLIENT) - void renderStatic(int x, int y, int z, IPartRenderHelper instance, RenderBlocks renderer, IFacadeContainer fc, AxisAlignedBB busBounds, boolean renderStilt); + @SideOnly( Side.CLIENT ) + void renderStatic( int x, int y, int z, IPartRenderHelper instance, RenderBlocks renderer, IFacadeContainer fc, AxisAlignedBB busBounds, boolean renderStilt ); /** * render the part in inventory. @@ -76,8 +77,8 @@ public interface IFacadePart * @param instance render helper * @param renderer renderer */ - @SideOnly(Side.CLIENT) - void renderInventory(IPartRenderHelper instance, RenderBlocks renderer); + @SideOnly( Side.CLIENT ) + void renderInventory( IPartRenderHelper instance, RenderBlocks renderer ); /** * @return side the facade is in @@ -95,8 +96,7 @@ public interface IFacadePart boolean isBC(); - void setThinFacades(boolean useThinFacades); + void setThinFacades( boolean useThinFacades ); boolean isTransparent(); - } \ No newline at end of file diff --git a/src/api/java/appeng/api/parts/IPartCollisionHelper.java b/src/api/java/appeng/api/parts/IPartCollisionHelper.java index ba923556b..f790a5d51 100644 --- a/src/api/java/appeng/api/parts/IPartCollisionHelper.java +++ b/src/api/java/appeng/api/parts/IPartCollisionHelper.java @@ -23,8 +23,10 @@ package appeng.api.parts; + import net.minecraftforge.common.util.ForgeDirection; + public interface IPartCollisionHelper { @@ -40,7 +42,7 @@ public interface IPartCollisionHelper * @param maxY maximal y collision * @param maxZ maximal z collision */ - void addBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ); + void addBox( double minX, double minY, double minZ, double maxX, double maxY, double maxZ ); /** * @return east in world space. @@ -61,5 +63,4 @@ public interface IPartCollisionHelper * @return true if this test is to get the BB Collision information. */ boolean isBBCollision(); - } diff --git a/src/api/java/appeng/api/parts/IPartHelper.java b/src/api/java/appeng/api/parts/IPartHelper.java index 9eeb8acac..2487d8c5d 100644 --- a/src/api/java/appeng/api/parts/IPartHelper.java +++ b/src/api/java/appeng/api/parts/IPartHelper.java @@ -23,10 +23,12 @@ package appeng.api.parts; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; + public interface IPartHelper { @@ -54,28 +56,29 @@ public interface IPartHelper * implement that interface on a part get implement it. * * @return true on success, false on failure, usually a error will be logged - * as well. + * as well. */ - boolean registerNewLayer(String string, String layerInterface); + boolean registerNewLayer( String string, String layerInterface ); /** * Register IBusItem with renderer */ - void setItemBusRenderer(IPartItem i); + void setItemBusRenderer( IPartItem i ); /** * use in use item, to try and place a IBusItem * - * @param is ItemStack of an item which implements {@link IPartItem} - * @param x x pos of part - * @param y y pos of part - * @param z z pos of part - * @param side side which the part should be on + * @param is ItemStack of an item which implements {@link IPartItem} + * @param x x pos of part + * @param y y pos of part + * @param z z pos of part + * @param side side which the part should be on * @param player player placing part - * @param world part in world + * @param world part in world + * * @return true if placing was successful */ - boolean placeBus(ItemStack is, int x, int y, int z, int side, EntityPlayer player, World world); + boolean placeBus( ItemStack is, int x, int y, int z, int side, EntityPlayer player, World world ); /** * @return the render mode diff --git a/src/api/java/appeng/api/parts/IPartHost.java b/src/api/java/appeng/api/parts/IPartHost.java index e85661591..4242dc811 100644 --- a/src/api/java/appeng/api/parts/IPartHost.java +++ b/src/api/java/appeng/api/parts/IPartHost.java @@ -35,6 +35,7 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; + /** * Implemented on AE's TileEntity or AE's FMP Part. * @@ -54,28 +55,31 @@ public interface IPartHost * * @param part to be added part * @param side part placed onto side + * * @return returns false if the part cannot be added. */ - boolean canAddPart(ItemStack part, ForgeDirection side); + boolean canAddPart( ItemStack part, ForgeDirection side ); /** * try to add a new part to the specified side, returns false if it failed to be added. * - * @param is new part - * @param side onto side + * @param is new part + * @param side onto side * @param owner with owning player + * * @return null if the item failed to add, the side it was placed on other wise ( may different for cables, - * {@link ForgeDirection}.UNKNOWN ) + * {@link ForgeDirection}.UNKNOWN ) */ - ForgeDirection addPart(ItemStack is, ForgeDirection side, EntityPlayer owner); + ForgeDirection addPart( ItemStack is, ForgeDirection side, EntityPlayer owner ); /** * Get part by side ( center is {@link ForgeDirection}.UNKNOWN ) * * @param side side of part + * * @return the part located on the specified side, or null if there is no part. */ - IPart getPart(ForgeDirection side); + IPart getPart( ForgeDirection side ); /** * removes the part on the side, this doesn't drop it or anything, if you don't do something with it, its just @@ -83,11 +87,10 @@ public interface IPartHost * * if you want to drop the part you must request it prior to removing it. * - * @param side side of part - * @param suppressUpdate - * - used if you need to replace a part's INSTANCE, without really removing it first. + * @param side side of part + * @param suppressUpdate - used if you need to replace a part's INSTANCE, without really removing it first. */ - void removePart(ForgeDirection side, boolean suppressUpdate); + void removePart( ForgeDirection side, boolean suppressUpdate ); /** * something changed, might want to send a packet to clients to update state. @@ -106,7 +109,7 @@ public interface IPartHost /** * @return the color of the host type ( this is determined by the middle cable. ) if no cable is present, it returns - * {@link AEColor} .Transparent other wise it returns the color of the cable in the center. + * {@link AEColor} .Transparent other wise it returns the color of the cable in the center. */ AEColor getColor(); @@ -120,15 +123,16 @@ public interface IPartHost * * @return returns if microblocks are blocking this cable path. */ - boolean isBlocked(ForgeDirection side); + boolean isBlocked( ForgeDirection side ); /** * finds the part located at the position ( pos must be relative, not global ) * * @param pos part position + * * @return a new SelectedPart, this is never null. */ - SelectedPart selectPart(Vec3 pos); + SelectedPart selectPart( Vec3 pos ); /** * can be used by parts to trigger the tile or part to save. @@ -144,9 +148,10 @@ public interface IPartHost * get the redstone state of host on this side, this value is cached internally. * * @param side side of part + * * @return true of the part host is receiving redstone from an external source. */ - boolean hasRedstone(ForgeDirection side); + boolean hasRedstone( ForgeDirection side ); /** * returns false if this block contains any parts or facades, true other wise. diff --git a/src/api/java/appeng/api/parts/IPartItem.java b/src/api/java/appeng/api/parts/IPartItem.java index 019fcf2b7..dc755477f 100644 --- a/src/api/java/appeng/api/parts/IPartItem.java +++ b/src/api/java/appeng/api/parts/IPartItem.java @@ -26,8 +26,9 @@ package appeng.api.parts; import net.minecraft.item.ItemStack; - //@formatter:off + + /** * This is a pretty basic requirement, once you implement the interface, and createPartFromItemStack * @@ -51,7 +52,6 @@ import net.minecraft.item.ItemStack; * } * * - * */ public interface IPartItem { diff --git a/src/api/java/appeng/api/parts/IPartRenderHelper.java b/src/api/java/appeng/api/parts/IPartRenderHelper.java index c107df082..b02e54565 100644 --- a/src/api/java/appeng/api/parts/IPartRenderHelper.java +++ b/src/api/java/appeng/api/parts/IPartRenderHelper.java @@ -34,6 +34,7 @@ import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + public interface IPartRenderHelper { @@ -49,83 +50,83 @@ public interface IPartRenderHelper * @param maxY maximal y bound * @param maxZ maximal z bound */ - void setBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); + void setBounds( float minX, float minY, float minZ, float maxX, float maxY, float maxZ ); /** * static renderer * * render a single face. * - * @param x x coord of part - * @param y y coord of part - * @param z z coord of part - * @param ico icon of part - * @param face direction its facing + * @param x x coord of part + * @param y y coord of part + * @param z z coord of part + * @param ico icon of part + * @param face direction its facing * @param renderer renderer of part */ - @SideOnly(Side.CLIENT) - void renderFace(int x, int y, int z, IIcon ico, ForgeDirection face, RenderBlocks renderer); + @SideOnly( Side.CLIENT ) + void renderFace( int x, int y, int z, IIcon ico, ForgeDirection face, RenderBlocks renderer ); /** * static renderer * * render a box with a cut out box in the center. * - * @param x x pos of part - * @param y y pos of part - * @param z z pos of part - * @param ico icon of part - * @param face face of part + * @param x x pos of part + * @param y y pos of part + * @param z z pos of part + * @param ico icon of part + * @param face face of part * @param edgeThickness thickness of the edge - * @param renderer renderer + * @param renderer renderer */ - @SideOnly(Side.CLIENT) - void renderFaceCutout(int x, int y, int z, IIcon ico, ForgeDirection face, float edgeThickness, RenderBlocks renderer); + @SideOnly( Side.CLIENT ) + void renderFaceCutout( int x, int y, int z, IIcon ico, ForgeDirection face, float edgeThickness, RenderBlocks renderer ); /** * static renderer * * render a block of specified bounds. * - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block * @param renderer renderer */ - @SideOnly(Side.CLIENT) - void renderBlock(int x, int y, int z, RenderBlocks renderer); + @SideOnly( Side.CLIENT ) + void renderBlock( int x, int y, int z, RenderBlocks renderer ); /** * render a single face in inventory renderer. * - * @param IIcon icon of part + * @param IIcon icon of part * @param direction face of part - * @param renderer renderer + * @param renderer renderer */ - @SideOnly(Side.CLIENT) - void renderInventoryFace(IIcon IIcon, ForgeDirection direction, RenderBlocks renderer); + @SideOnly( Side.CLIENT ) + void renderInventoryFace( IIcon IIcon, ForgeDirection direction, RenderBlocks renderer ); /** * render a box in inventory renderer. * * @param renderer renderer */ - @SideOnly(Side.CLIENT) - void renderInventoryBox(RenderBlocks renderer); + @SideOnly( Side.CLIENT ) + void renderInventoryBox( RenderBlocks renderer ); /** * inventory, and static renderer. * * set unique icons for each side of the block. * - * @param down down face - * @param up up face + * @param down down face + * @param up up face * @param north north face * @param south south face - * @param west west face - * @param east east face + * @param west west face + * @param east east face */ - void setTexture(IIcon down, IIcon up, IIcon north, IIcon south, IIcon west, IIcon east); + void setTexture( IIcon down, IIcon up, IIcon north, IIcon south, IIcon west, IIcon east ); /** * inventory, and static renderer. @@ -134,14 +135,14 @@ public interface IPartRenderHelper * * @param ico to be set icon */ - void setTexture(IIcon ico); + void setTexture( IIcon ico ); /** * configure the color multiplier for the inventory renderer. * * @param whiteVariant color multiplier */ - void setInvColor(int whiteVariant); + void setInvColor( int whiteVariant ); /** * @return the block used for rendering, might need it for some reason... @@ -169,7 +170,7 @@ public interface IPartRenderHelper * * Only worth it if you render more then 1 block. */ - ISimplifiedBundle useSimplifiedRendering(int x, int y, int z, IBoxProvider p, ISimplifiedBundle sim); + ISimplifiedBundle useSimplifiedRendering( int x, int y, int z, IBoxProvider p, ISimplifiedBundle sim ); /** * disables, useSimplifiedRendering. @@ -179,25 +180,24 @@ public interface IPartRenderHelper /** * render a block using the current renderer state. * - * @param x x pos of part - * @param y y pos of part - * @param z z pos of part + * @param x x pos of part + * @param y y pos of part + * @param z z pos of part * @param renderer renderer of part */ - void renderBlockCurrentBounds(int x, int y, int z, RenderBlocks renderer); + void renderBlockCurrentBounds( int x, int y, int z, RenderBlocks renderer ); /** * allow you to enable your part to render during the alpha pass or the standard pass. * * @param pass render pass */ - void renderForPass(int pass); + void renderForPass( int pass ); /** * Set which faces to render, remember to set back to ALL when you are done. * * @param complementOf sides to render */ - void setFacesToRender(EnumSet complementOf); - + void setFacesToRender( EnumSet complementOf ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/parts/LayerBase.java b/src/api/java/appeng/api/parts/LayerBase.java index a89bc007a..91ca0f000 100644 --- a/src/api/java/appeng/api/parts/LayerBase.java +++ b/src/api/java/appeng/api/parts/LayerBase.java @@ -29,6 +29,7 @@ import java.util.Set; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; + /** * All Layers must extends this, this get part implementation is provided to interface with the parts, however a real * implementation will be used at runtime. @@ -42,9 +43,10 @@ public abstract class LayerBase extends TileEntity // implements IPartHost * This Method looks silly, that is because its not used at runtime, a real implementation will be used instead. * * @param side side of part + * * @return the part for the requested side. */ - public IPart getPart(ForgeDirection side) + public IPart getPart( ForgeDirection side ) { return null; // place holder. } @@ -75,5 +77,4 @@ public abstract class LayerBase extends TileEntity // implements IPartHost { // something! } - } diff --git a/src/api/java/appeng/api/recipes/ICraftHandler.java b/src/api/java/appeng/api/recipes/ICraftHandler.java index 1ab1d6888..66f442775 100644 --- a/src/api/java/appeng/api/recipes/ICraftHandler.java +++ b/src/api/java/appeng/api/recipes/ICraftHandler.java @@ -30,14 +30,16 @@ import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; + public interface ICraftHandler { /** * Called when your recipe handler receives a newly parsed list of inputs/outputs. * - * @param input parsed inputs + * @param input parsed inputs * @param output parsed outputs + * * @throws RecipeError */ void setup( List> input, List> output ) throws RecipeError; @@ -49,5 +51,4 @@ public interface ICraftHandler * @throws MissingIngredientError */ void register() throws RegistrationError, MissingIngredientError; - } diff --git a/src/api/java/appeng/api/recipes/IIngredient.java b/src/api/java/appeng/api/recipes/IIngredient.java index 30fcdef40..2878022d3 100644 --- a/src/api/java/appeng/api/recipes/IIngredient.java +++ b/src/api/java/appeng/api/recipes/IIngredient.java @@ -29,7 +29,9 @@ import net.minecraft.item.ItemStack; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; -public interface IIngredient { + +public interface IIngredient +{ /** * Acquire a single input stack for the current recipe, if more then one ItemStack is possible a @@ -47,6 +49,7 @@ public interface IIngredient { * multiple inputs per slot. * * @return an array of ItemStacks for the recipe handler. + * * @throws RegistrationError * @throws MissingIngredientError */ @@ -81,9 +84,9 @@ public interface IIngredient { /** * Bakes the lists in for faster runtime look-ups. + * * @throws MissingIngredientError * @throws RegistrationError */ void bake() throws RegistrationError, MissingIngredientError; - } diff --git a/src/api/java/appeng/api/storage/ICellHandler.java b/src/api/java/appeng/api/storage/ICellHandler.java index bec954dbb..e2207c9fc 100644 --- a/src/api/java/appeng/api/storage/ICellHandler.java +++ b/src/api/java/appeng/api/storage/ICellHandler.java @@ -33,6 +33,7 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.api.implementations.tiles.IChestOrDrive; + /** * Registration record for {@link ICellRegistry} */ @@ -44,63 +45,60 @@ public interface ICellHandler * request a handler ) * * @param is to be checked item + * * @return return true, if getCellHandler will not return null. */ - boolean isCell(ItemStack is); + boolean isCell( ItemStack is ); /** * If you cannot handle the provided item, return null * - * @param is - * a storage cell item. - * @param host - * anytime the contents of your storage cell changes it should use this to request a save, please - * note, this value can be null. - * @param channel - * the storage channel requested. + * @param is a storage cell item. + * @param host anytime the contents of your storage cell changes it should use this to request a save, please + * note, this value can be null. + * @param channel the storage channel requested. * * @return a new IMEHandler for the provided item */ - IMEInventoryHandler getCellInventory(ItemStack is, ISaveProvider host, StorageChannel channel); + IMEInventoryHandler getCellInventory( ItemStack is, ISaveProvider host, StorageChannel channel ); /** * @return the ME Chest texture for light pixels this storage cell type, should be 10x10 with 3px of transparent - * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the - * assets for examples. + * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the + * assets for examples. */ - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) IIcon getTopTexture_Light(); /** * @return the ME Chest texture for medium pixels this storage cell type, should be 10x10 with 3px of transparent - * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the - * assets for examples. + * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the + * assets for examples. */ - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) IIcon getTopTexture_Medium(); /** * @return the ME Chest texture for dark pixels this storage cell type, should be 10x10 with 3px of transparent - * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the - * assets for examples. + * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the + * assets for examples. */ - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) IIcon getTopTexture_Dark(); /** - * * Called when the storage cell is planed in an ME Chest and the user tries to open the terminal side, if your item * is not available via ME Chests simply tell the user they can't use it, or something, other wise you should open * your gui and display the cell to the user. * - * @param player player opening chest gui - * @param chest to be opened chest + * @param player player opening chest gui + * @param chest to be opened chest * @param cellHandler cell handler - * @param inv inventory handler - * @param is item - * @param chan storage channel + * @param inv inventory handler + * @param is item + * @param chan storage channel */ - void openChestGui(EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan); + void openChestGui( EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan ); /** * 0 - cell is missing. @@ -111,16 +109,15 @@ public interface ICellHandler * * 3 - red, ( usually means the cell is 100% full ) * - * @param is the cell item. ( use the handler for any details you can ) + * @param is the cell item. ( use the handler for any details you can ) * @param handler the handler for the cell is provides for reference, you can cast this to your handler. * * @return get the status of the cell based on its contents. */ - int getStatusForCell(ItemStack is, IMEInventory handler); + int getStatusForCell( ItemStack is, IMEInventory handler ); /** * @return the ae/t to drain for this storage cell inside a chest/drive. */ - double cellIdleDrain(ItemStack is, IMEInventory handler); - + double cellIdleDrain( ItemStack is, IMEInventory handler ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/storage/ICellProvider.java b/src/api/java/appeng/api/storage/ICellProvider.java index fab409706..af849bf41 100644 --- a/src/api/java/appeng/api/storage/ICellProvider.java +++ b/src/api/java/appeng/api/storage/ICellProvider.java @@ -23,8 +23,10 @@ package appeng.api.storage; + import java.util.List; + /** * Allows you to provide cells via non IGridHosts directly to the storage system, drives, and similar features should go * though {@link ICellContainer} and be automatically handled by the storage system. @@ -40,7 +42,7 @@ public interface ICellProvider * * @return a valid list of handlers, NEVER NULL */ - List getCellArray(StorageChannel channel); + List getCellArray( StorageChannel channel ); /** * the storage's priority. @@ -48,5 +50,4 @@ public interface ICellProvider * Positive and negative are supported */ int getPriority(); - } diff --git a/src/api/java/appeng/api/storage/ICellRegistry.java b/src/api/java/appeng/api/storage/ICellRegistry.java index 2b5aa7f47..406bfd225 100644 --- a/src/api/java/appeng/api/storage/ICellRegistry.java +++ b/src/api/java/appeng/api/storage/ICellRegistry.java @@ -28,6 +28,7 @@ import net.minecraft.item.ItemStack; import appeng.api.IAppEngApi; + /** * Storage Cell Registry, used for specially implemented cells, if you just want to make a item act like a cell, or new * cell with different bytes, then you should probably consider IStorageCell instead its considerably simpler. @@ -42,34 +43,35 @@ public interface ICellRegistry * * @param handler cell handler */ - void addCellHandler(ICellHandler handler); + void addCellHandler( ICellHandler handler ); /** * return true, if you can get a InventoryHandler for the item passed. * * @param is to be checked item + * * @return true if the provided item, can be handled by a handler in AE, ( AE May choose to skip this and just get - * the handler instead. ) + * the handler instead. ) */ - boolean isCellHandled(ItemStack is); + boolean isCellHandled( ItemStack is ); /** * get the handler, for the requested type. * * @param is to be checked item + * * @return the handler registered for this item type. */ - ICellHandler getHandler(ItemStack is); + ICellHandler getHandler( ItemStack is ); /** * returns an IMEInventoryHandler for the provided item. * - * @param is item with inventory handler + * @param is item with inventory handler * @param host can be null, or the hosting tile / part. * @param chan the storage channel to request the handler for. * * @return new IMEInventoryHandler, or null if there isn't one. */ - IMEInventoryHandler getCellInventory(ItemStack is, ISaveProvider host, StorageChannel chan); - + IMEInventoryHandler getCellInventory( ItemStack is, ISaveProvider host, StorageChannel chan ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/storage/ICellWorkbenchItem.java b/src/api/java/appeng/api/storage/ICellWorkbenchItem.java index 386893e24..668095c6e 100644 --- a/src/api/java/appeng/api/storage/ICellWorkbenchItem.java +++ b/src/api/java/appeng/api/storage/ICellWorkbenchItem.java @@ -29,6 +29,7 @@ import net.minecraft.item.ItemStack; import appeng.api.config.FuzzyMode; + public interface ICellWorkbenchItem { @@ -36,9 +37,10 @@ public interface ICellWorkbenchItem * if this return false, the item will not be treated as a cell, and cannot be inserted into the work bench. * * @param is item + * * @return true if the item should be editable in the cell workbench. */ - boolean isEditable(ItemStack is); + boolean isEditable( ItemStack is ); /** * used to edit the upgrade slots on your cell, should have a capacity of 0-24, you are also responsible for @@ -46,7 +48,7 @@ public interface ICellWorkbenchItem * * onInventoryChange will be called when saving is needed. */ - IInventory getUpgradesInventory(ItemStack is); + IInventory getUpgradesInventory( ItemStack is ); /** * Used to extract, or mirror the contents of the work bench onto the cell. @@ -55,16 +57,15 @@ public interface ICellWorkbenchItem * * onInventoryChange will be called when saving is needed. */ - IInventory getConfigInventory(ItemStack is); + IInventory getConfigInventory( ItemStack is ); /** * @return the current fuzzy status. */ - FuzzyMode getFuzzyMode(ItemStack is); + FuzzyMode getFuzzyMode( ItemStack is ); /** * sets the setting on the cell. */ - void setFuzzyMode(ItemStack is, FuzzyMode fzMode); - + void setFuzzyMode( ItemStack is, FuzzyMode fzMode ); } diff --git a/src/api/java/appeng/api/storage/IExternalStorageHandler.java b/src/api/java/appeng/api/storage/IExternalStorageHandler.java index d5ae652fb..484864a3e 100644 --- a/src/api/java/appeng/api/storage/IExternalStorageHandler.java +++ b/src/api/java/appeng/api/storage/IExternalStorageHandler.java @@ -29,6 +29,7 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.networking.security.BaseActionSource; + /** * A Registration Record for {@link IExternalStorageRegistry} */ @@ -39,11 +40,12 @@ public interface IExternalStorageHandler * if this can handle the provided inventory, return true. ( Generally skipped by AE, and it just calls getInventory * ) * - * @param te to be handled tile entity + * @param te to be handled tile entity * @param mySrc source + * * @return true, if it can get a handler via getInventory */ - boolean canHandle(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc); + boolean canHandle( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc ); /** * if this can handle the given inventory, return the a IMEInventory implementing class for it, if not return null @@ -51,12 +53,12 @@ public interface IExternalStorageHandler * please note that if your inventory changes and requires polling, you must use an {@link IMEMonitor} instead of an * {@link IMEInventory} failure to do so will result in invalid item counts and reporting of the inventory. * - * @param te to be handled tile entity - * @param d direction + * @param te to be handled tile entity + * @param d direction * @param channel channel - * @param src source + * @param src source + * * @return The Handler for the inventory */ - IMEInventory getInventory(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src); - + IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/storage/IExternalStorageRegistry.java b/src/api/java/appeng/api/storage/IExternalStorageRegistry.java index fb7955e0c..127c7b5ac 100644 --- a/src/api/java/appeng/api/storage/IExternalStorageRegistry.java +++ b/src/api/java/appeng/api/storage/IExternalStorageRegistry.java @@ -30,6 +30,7 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.IAppEngApi; import appeng.api.networking.security.BaseActionSource; + /** * A Registry of External Storage handlers. * @@ -43,15 +44,15 @@ public interface IExternalStorageRegistry * * @param esh storage handler */ - void addExternalStorageInterface(IExternalStorageHandler esh); + void addExternalStorageInterface( IExternalStorageHandler esh ); /** - * @param te tile entity + * @param te tile entity * @param opposite direction - * @param channel channel - * @param mySrc source + * @param channel channel + * @param mySrc source + * * @return the handler for a given tile / forge direction */ - IExternalStorageHandler getHandler(TileEntity te, ForgeDirection opposite, StorageChannel channel, BaseActionSource mySrc); - + IExternalStorageHandler getHandler( TileEntity te, ForgeDirection opposite, StorageChannel channel, BaseActionSource mySrc ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/storage/IMEInventory.java b/src/api/java/appeng/api/storage/IMEInventory.java index 54128bc26..58ff46c62 100644 --- a/src/api/java/appeng/api/storage/IMEInventory.java +++ b/src/api/java/appeng/api/storage/IMEInventory.java @@ -23,11 +23,13 @@ package appeng.api.storage; + import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; + /** * AE's Equivalent to IInventory, used to reading contents, and manipulating contents of ME Inventories. * @@ -45,8 +47,9 @@ public interface IMEInventory * Store new items, or simulate the addition of new items into the ME Inventory. * * @param input item to add. - * @param type action type - * @param src action source + * @param type action type + * @param src action source + * * @return returns the number of items not added. */ StackType injectItems( StackType input, Actionable type, BaseActionSource src ); @@ -54,10 +57,9 @@ public interface IMEInventory /** * Extract the specified item from the ME Inventory * - * @param request - * item to request ( with stack size. ) - * @param mode - * simulate, or perform action? + * @param request item to request ( with stack size. ) + * @param mode simulate, or perform action? + * * @return returns the number of items extracted, null */ StackType extractItems( StackType request, Actionable mode, BaseActionSource src ); @@ -65,8 +67,8 @@ public interface IMEInventory /** * request a full report of all available items, storage. * - * @param out - * the IItemList the results will be written too + * @param out the IItemList the results will be written too + * * @return returns same list that was passed in, is passed out */ IItemList getAvailableItems( IItemList out ); @@ -75,5 +77,4 @@ public interface IMEInventory * @return the type of channel your handler should be part of */ StorageChannel getChannel(); - } diff --git a/src/api/java/appeng/api/storage/IMEInventoryHandler.java b/src/api/java/appeng/api/storage/IMEInventoryHandler.java index 47eb8aced..f77409173 100644 --- a/src/api/java/appeng/api/storage/IMEInventoryHandler.java +++ b/src/api/java/appeng/api/storage/IMEInventoryHandler.java @@ -23,9 +23,11 @@ package appeng.api.storage; + import appeng.api.config.AccessRestriction; import appeng.api.storage.data.IAEStack; + /** * Thin logic layer that can be swapped with different IMEInventory implementations, used to handle features related to * storage, that are Separate from the storage medium itself. @@ -46,8 +48,8 @@ public interface IMEInventoryHandler extends IMEInve * determine if a particular item is prioritized for this inventory handler, if it is, then it will be added to this * inventory prior to any non-prioritized inventories. * - * @param input - * - item that might be added + * @param input - item that might be added + * * @return if its prioritized */ boolean isPrioritized( StackType input ); @@ -55,8 +57,8 @@ public interface IMEInventoryHandler extends IMEInve /** * determine if an item can be accepted and stored. * - * @param input - * - item that might be added + * @param input - item that might be added + * * @return if the item can be added */ boolean canAccept( StackType input ); @@ -72,8 +74,8 @@ public interface IMEInventoryHandler extends IMEInve * pass back value for blinkCell. * * @return the slot index for the cell that this represents in the storage unit, the method on the - * {@link ICellContainer} will be called with this value, only trust the return value of this method if you - * are the implementer of this. + * {@link ICellContainer} will be called with this value, only trust the return value of this method if you + * are the implementer of this. */ int getSlot(); @@ -82,8 +84,8 @@ public interface IMEInventoryHandler extends IMEInve * belongs, however in some cases you can save processor time, or require that the second, or first pass is simply * ignored, this allows you to do that. * - * @param i - * - pass number ( 1 or 2 ) + * @param i - pass number ( 1 or 2 ) + * * @return true, if this inventory is valid for this pass. */ boolean validForPass( int i ); diff --git a/src/api/java/appeng/api/storage/IStorageHelper.java b/src/api/java/appeng/api/storage/IStorageHelper.java index fa8693c5a..c75eac221 100644 --- a/src/api/java/appeng/api/storage/IStorageHelper.java +++ b/src/api/java/appeng/api/storage/IStorageHelper.java @@ -40,6 +40,7 @@ import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; + public interface IStorageHelper { @@ -47,25 +48,24 @@ public interface IStorageHelper * load a crafting link from nbt data. * * @param data to be loaded data + * * @return crafting link */ - ICraftingLink loadCraftingLink(NBTTagCompound data, ICraftingRequester req); + ICraftingLink loadCraftingLink( NBTTagCompound data, ICraftingRequester req ); /** - * @param is - * An ItemStack + * @param is An ItemStack * * @return a new INSTANCE of {@link IAEItemStack} from a MC {@link ItemStack} */ - IAEItemStack createItemStack(ItemStack is); + IAEItemStack createItemStack( ItemStack is ); /** - * @param is - * A FluidStack + * @param is A FluidStack * * @return a new INSTANCE of {@link IAEFluidStack} from a Forge {@link FluidStack} */ - IAEFluidStack createFluidStack(FluidStack is); + IAEFluidStack createFluidStack( FluidStack is ); /** * @return a new INSTANCE of {@link IItemList} for items @@ -81,40 +81,45 @@ public interface IStorageHelper * Read a AE Item Stack from a byte stream, returns a AE item stack or null. * * @param input to be loaded data + * * @return item based of data + * * @throws IOException if file could not be read */ - IAEItemStack readItemFromPacket(ByteBuf input) throws IOException; + IAEItemStack readItemFromPacket( ByteBuf input ) throws IOException; /** * Read a AE Fluid Stack from a byte stream, returns a AE fluid stack or null. * * @param input to be loaded data + * * @return fluid based on data + * * @throws IOException if file could not be written */ - IAEFluidStack readFluidFromPacket(ByteBuf input) throws IOException; + IAEFluidStack readFluidFromPacket( ByteBuf input ) throws IOException; /** * use energy from energy, to remove request items from cell, at the request of src. * - * @param energy to be drained energy source - * @param cell cell of requested items + * @param energy to be drained energy source + * @param cell cell of requested items * @param request requested items - * @param src action source + * @param src action source + * * @return items that successfully extracted. */ - IAEItemStack poweredExtraction(IEnergySource energy, IMEInventory cell, IAEItemStack request, BaseActionSource src); + IAEItemStack poweredExtraction( IEnergySource energy, IMEInventory cell, IAEItemStack request, BaseActionSource src ); /** * use energy from energy, to inject input items into cell, at the request of src * * @param energy to be added energy source - * @param cell injected cell - * @param input to be injected items - * @param src action source + * @param cell injected cell + * @param input to be injected items + * @param src action source + * * @return items that failed to insert. */ - IAEItemStack poweredInsert(IEnergySource energy, IMEInventory cell, IAEItemStack input, BaseActionSource src); - + IAEItemStack poweredInsert( IEnergySource energy, IMEInventory cell, IAEItemStack input, BaseActionSource src ); } diff --git a/src/api/java/appeng/api/storage/IStorageMonitorable.java b/src/api/java/appeng/api/storage/IStorageMonitorable.java index be58fef42..3a832c5f0 100644 --- a/src/api/java/appeng/api/storage/IStorageMonitorable.java +++ b/src/api/java/appeng/api/storage/IStorageMonitorable.java @@ -23,10 +23,12 @@ package appeng.api.storage; + import appeng.api.implementations.tiles.ITileStorageMonitorable; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; + /** * represents the internal behavior of a {@link ITileStorageMonitorable} use it to get this value for a tile, or part. * @@ -44,5 +46,4 @@ public interface IStorageMonitorable * Access the fluid inventory for the monitorable storage. */ IMEMonitor getFluidInventory(); - } diff --git a/src/api/java/appeng/api/storage/MEMonitorHandler.java b/src/api/java/appeng/api/storage/MEMonitorHandler.java index 733a11cf3..5b6ba0b3d 100644 --- a/src/api/java/appeng/api/storage/MEMonitorHandler.java +++ b/src/api/java/appeng/api/storage/MEMonitorHandler.java @@ -36,6 +36,7 @@ import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; + /** * Common implementation of a simple class that monitors injection/extraction of a inventory to send events to a list of * listeners. @@ -51,106 +52,89 @@ public class MEMonitorHandler implements IMEMonitor< protected boolean hasChanged = true; + public MEMonitorHandler( IMEInventoryHandler t ) + { + this.internalHandler = t; + this.cachedList = (IItemList) t.getChannel().createList(); + } + + public MEMonitorHandler( IMEInventoryHandler t, StorageChannel chan ) + { + this.internalHandler = t; + this.cachedList = (IItemList) chan.createList(); + } + + @Override + public void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ) + { + this.listeners.put( l, verificationToken ); + } + + @Override + public void removeListener( IMEMonitorHandlerReceiver l ) + { + this.listeners.remove( l ); + } + + @Override + public StackType injectItems( StackType input, Actionable mode, BaseActionSource src ) + { + if( mode == Actionable.SIMULATE ) + return this.getHandler().injectItems( input, mode, src ); + return this.monitorDifference( input.copy(), this.getHandler().injectItems( input, mode, src ), false, src ); + } + protected IMEInventoryHandler getHandler() { return this.internalHandler; } + private StackType monitorDifference( IAEStack original, StackType leftOvers, boolean extraction, BaseActionSource src ) + { + StackType diff = (StackType) original.copy(); + + if( extraction ) + diff.setStackSize( leftOvers == null ? 0 : -leftOvers.getStackSize() ); + else if( leftOvers != null ) + diff.decStackSize( leftOvers.getStackSize() ); + + if( diff.getStackSize() != 0 ) + this.postChangesToListeners( ImmutableList.of( diff ), src ); + + return leftOvers; + } + + protected void postChangesToListeners( Iterable changes, BaseActionSource src ) + { + this.notifyListenersOfChange( changes, src ); + } + + protected void notifyListenersOfChange( Iterable diff, BaseActionSource src ) + { + this.hasChanged = true;// need to update the cache. + Iterator, Object>> i = this.getListeners(); + while( i.hasNext() ) + { + Entry, Object> o = i.next(); + IMEMonitorHandlerReceiver receiver = o.getKey(); + if( receiver.isValid( o.getValue() ) ) + receiver.postChange( this, diff, src ); + else + i.remove(); + } + } + protected Iterator, Object>> getListeners() { return this.listeners.entrySet().iterator(); } - protected void postChangesToListeners( Iterable changes, BaseActionSource src) - { - this.notifyListenersOfChange( changes, src ); - } - - protected void notifyListenersOfChange(Iterable diff, BaseActionSource src) - { - this.hasChanged = true;// need to update the cache. - Iterator, Object>> i = this.getListeners(); - while (i.hasNext()) - { - Entry, Object> o = i.next(); - IMEMonitorHandlerReceiver receiver = o.getKey(); - if ( receiver.isValid( o.getValue() ) ) - receiver.postChange( this, diff, src ); - else - i.remove(); - } - } - - private StackType monitorDifference(IAEStack original, StackType leftOvers, boolean extraction, BaseActionSource src) - { - StackType diff = (StackType) original.copy(); - - if ( extraction ) - diff.setStackSize( leftOvers == null ? 0 : -leftOvers.getStackSize() ); - else if ( leftOvers != null ) - diff.decStackSize( leftOvers.getStackSize() ); - - if ( diff.getStackSize() != 0 ) - this.postChangesToListeners( ImmutableList.of( diff ), src ); - - return leftOvers; - } - - public MEMonitorHandler(IMEInventoryHandler t) { - this.internalHandler = t; - this.cachedList = (IItemList) t.getChannel().createList(); - } - - public MEMonitorHandler(IMEInventoryHandler t, StorageChannel chan) { - this.internalHandler = t; - this.cachedList = (IItemList) chan.createList(); - } - @Override - public void addListener(IMEMonitorHandlerReceiver l, Object verificationToken) + public StackType extractItems( StackType request, Actionable mode, BaseActionSource src ) { - this.listeners.put( l, verificationToken ); - } - - @Override - public void removeListener(IMEMonitorHandlerReceiver l) - { - this.listeners.remove( l ); - } - - @Override - public StackType injectItems(StackType input, Actionable mode, BaseActionSource src) - { - if ( mode == Actionable.SIMULATE ) - return this.getHandler().injectItems( input, mode, src ); - return this.monitorDifference(input.copy(), this.getHandler().injectItems(input, mode, src), false, src); - } - - @Override - public StackType extractItems(StackType request, Actionable mode, BaseActionSource src) - { - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) return this.getHandler().extractItems( request, mode, src ); - return this.monitorDifference(request.copy(), this.getHandler().extractItems(request, mode, src), true, src); - } - - @Override - public IItemList getStorageList() - { - if ( this.hasChanged ) - { - this.hasChanged = false; - this.cachedList.resetStatus(); - return this.getAvailableItems( this.cachedList ); - } - - return this.cachedList; - } - - @Override - public IItemList getAvailableItems(IItemList out) - { - return this.getHandler().getAvailableItems( out ); + return this.monitorDifference( request.copy(), this.getHandler().extractItems( request, mode, src ), true, src ); } @Override @@ -163,18 +147,33 @@ public class MEMonitorHandler implements IMEMonitor< public AccessRestriction getAccess() { return this.getHandler().getAccess(); + } @Override + public IItemList getStorageList() + { + if( this.hasChanged ) + { + this.hasChanged = false; + this.cachedList.resetStatus(); + return this.getAvailableItems( this.cachedList ); + } + + return this.cachedList; } @Override - public boolean isPrioritized(StackType input) + public boolean isPrioritized( StackType input ) { return this.getHandler().isPrioritized( input ); } @Override - public boolean canAccept(StackType input) + public boolean canAccept( StackType input ) { return this.getHandler().canAccept( input ); + } @Override + public IItemList getAvailableItems( IItemList out ) + { + return this.getHandler().getAvailableItems( out ); } @Override @@ -190,9 +189,12 @@ public class MEMonitorHandler implements IMEMonitor< } @Override - public boolean validForPass(int i) + public boolean validForPass( int i ) { return this.getHandler().validForPass( i ); } + + + } diff --git a/src/api/java/appeng/api/storage/StorageChannel.java b/src/api/java/appeng/api/storage/StorageChannel.java index faaba20b9..b2131e554 100644 --- a/src/api/java/appeng/api/storage/StorageChannel.java +++ b/src/api/java/appeng/api/storage/StorageChannel.java @@ -45,14 +45,14 @@ public enum StorageChannel public final Class type; - StorageChannel( Class t ) + StorageChannel( Class t ) { this.type = t; } public IItemList createList() { - if ( this == ITEMS ) + if( this == ITEMS ) return AEApi.instance().storage().createItemList(); else return AEApi.instance().storage().createFluidList(); diff --git a/src/api/java/appeng/api/storage/data/IAEFluidStack.java b/src/api/java/appeng/api/storage/data/IAEFluidStack.java index 79e4136f7..b33bfa626 100644 --- a/src/api/java/appeng/api/storage/data/IAEFluidStack.java +++ b/src/api/java/appeng/api/storage/data/IAEFluidStack.java @@ -23,9 +23,11 @@ package appeng.api.storage.data; + import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; + /** * An alternate version of FluidStack for AE to keep tabs on things easier, and * to support larger storage. stackSizes of getFluidStack will be capped. @@ -36,7 +38,6 @@ import net.minecraftforge.fluids.FluidStack; * Don't Implement. * * Construct with Util.createFluidStack( FluidStack ) - * */ public interface IAEFluidStack extends IAEStack { @@ -48,6 +49,14 @@ public interface IAEFluidStack extends IAEStack */ FluidStack getFluidStack(); + /** + * Combines two IAEItemStacks via addition. + * + * @param option , to add to the current one. + */ + @Override + void add( IAEFluidStack option ); + /** * create a AE Fluid clone. * @@ -56,20 +65,10 @@ public interface IAEFluidStack extends IAEStack @Override IAEFluidStack copy(); - /** - * Combines two IAEItemStacks via addition. - * - * @param option - * , to add to the current one. - */ - @Override - void add(IAEFluidStack option); - /** * quick way to get access to the Forge Fluid Definition. * * @return fluid definition */ Fluid getFluid(); - } diff --git a/src/api/java/appeng/api/storage/data/IAEItemStack.java b/src/api/java/appeng/api/storage/data/IAEItemStack.java index 551806785..3da0fdb5b 100644 --- a/src/api/java/appeng/api/storage/data/IAEItemStack.java +++ b/src/api/java/appeng/api/storage/data/IAEItemStack.java @@ -23,9 +23,11 @@ package appeng.api.storage.data; + import net.minecraft.item.Item; import net.minecraft.item.ItemStack; + /** * An alternate version of ItemStack for AE to keep tabs on things easier, and to support larger storage. stackSizes of * getItemStack will be capped. @@ -46,14 +48,6 @@ public interface IAEItemStack extends IAEStack */ ItemStack getItemStack(); - /** - * create a AE Item clone - * - * @return the copy - */ - @Override - IAEItemStack copy(); - /** * is there NBT Data for this item? * @@ -64,11 +58,18 @@ public interface IAEItemStack extends IAEStack /** * Combines two IAEItemStacks via addition. * - * @param option - * to add to the current one. + * @param option to add to the current one. */ @Override - void add(IAEItemStack option); + void add( IAEItemStack option ); + + /** + * create a AE Item clone + * + * @return the copy + */ + @Override + IAEItemStack copy(); /** * quick way to get access to the MC Item Definition. @@ -85,21 +86,23 @@ public interface IAEItemStack extends IAEStack /** * Compare the Ore Dictionary ID for this to another item. */ - boolean sameOre(IAEItemStack is); + boolean sameOre( IAEItemStack is ); /** * compare the item/damage/nbt of the stack. * * @param otherStack to be compared item + * * @return true if it is the same type (same item, damage, nbt) */ - boolean isSameType(IAEItemStack otherStack); + boolean isSameType( IAEItemStack otherStack ); /** * compare the item/damage/nbt of the stack. * * @param stored to be compared item + * * @return true if it is the same type (same item, damage, nbt) */ - boolean isSameType(ItemStack stored); + boolean isSameType( ItemStack stored ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/storage/data/IAEStack.java b/src/api/java/appeng/api/storage/data/IAEStack.java index b3c6aad8f..e1db8a0fa 100644 --- a/src/api/java/appeng/api/storage/data/IAEStack.java +++ b/src/api/java/appeng/api/storage/data/IAEStack.java @@ -33,6 +33,7 @@ import net.minecraft.nbt.NBTTagCompound; import appeng.api.config.FuzzyMode; import appeng.api.storage.StorageChannel; + public interface IAEStack { @@ -41,7 +42,7 @@ public interface IAEStack * * @param is added item */ - void add(StackType is); + void add( StackType is ); /** * number of items in the stack. @@ -53,10 +54,9 @@ public interface IAEStack /** * changes the number of items in the stack. * - * @param stackSize - * , ItemStack.stackSize = N + * @param stackSize , ItemStack.stackSize = N */ - StackType setStackSize(long stackSize); + StackType setStackSize( long stackSize ); /** * Same as getStackSize, but for requestable items. ( LP ) @@ -70,7 +70,7 @@ public interface IAEStack * * @return basically itemStack.stackSize = N but for setStackSize items. */ - StackType setCountRequestable(long countRequestable); + StackType setCountRequestable( long countRequestable ); /** * true, if the item can be crafted. @@ -84,7 +84,7 @@ public interface IAEStack * * @param isCraftable can item be crafted */ - StackType setCraftable(boolean isCraftable); + StackType setCraftable( boolean isCraftable ); /** * clears, requestable, craftable, and stack sizes. @@ -103,33 +103,33 @@ public interface IAEStack * * @param i additional stack size */ - void incStackSize(long i); + void incStackSize( long i ); /** * removes some from the stack size. */ - void decStackSize(long i); + void decStackSize( long i ); /** * adds items to the requestable * * @param i increased amount of requested items */ - void incCountRequestable(long i); + void incCountRequestable( long i ); /** * removes items from the requestable * * @param i decreased amount of requested items */ - void decCountRequestable(long i); + void decCountRequestable( long i ); /** * write to a NBTTagCompound. * * @param i to be written data */ - void writeToNBT(NBTTagCompound i); + void writeToNBT( NBTTagCompound i ); /** * Compare stacks using precise logic. @@ -141,29 +141,32 @@ public interface IAEStack * IAEFluidStack, FluidStack * * @param obj compared object + * * @return true if they are the same. */ @Override - boolean equals(Object obj); + boolean equals( Object obj ); /** * compare stacks using fuzzy logic * * a IAEItemStack to another AEItemStack or a ItemStack. * - * @param st stacks + * @param st stacks * @param mode used fuzzy mode + * * @return true if two stacks are equal based on AE Fuzzy Comparison. */ - boolean fuzzyComparison(Object st, FuzzyMode mode); + boolean fuzzyComparison( Object st, FuzzyMode mode ); /** * Slower for disk saving, but smaller/more efficient for packets. * * @param data to be written data + * * @throws IOException */ - void writeToPacket(ByteBuf data) throws IOException; + void writeToPacket( ByteBuf data ) throws IOException; /** * Clone the Item / Fluid Stack @@ -200,5 +203,4 @@ public interface IAEStack * @return ITEM or FLUID */ StorageChannel getChannel(); - } diff --git a/src/api/java/appeng/api/storage/data/IAETagCompound.java b/src/api/java/appeng/api/storage/data/IAETagCompound.java index 1cfd60d4f..bd4b57b8b 100644 --- a/src/api/java/appeng/api/storage/data/IAETagCompound.java +++ b/src/api/java/appeng/api/storage/data/IAETagCompound.java @@ -28,6 +28,7 @@ import net.minecraft.nbt.NBTTagCompound; import appeng.api.features.IItemComparison; + /** * Don't cast this... either compare with it, or copy it. * @@ -45,14 +46,14 @@ public interface IAETagCompound * compare to other NBTTagCompounds or IAETagCompounds * * @param a compared object + * * @return true, if they are the same. */ @Override - boolean equals(Object a); + boolean equals( Object a ); /** * @return the special comparison for this tag */ IItemComparison getSpecialComparison(); - } \ No newline at end of file diff --git a/src/api/java/appeng/api/storage/data/IItemContainer.java b/src/api/java/appeng/api/storage/data/IItemContainer.java index a229b6572..049a52f87 100644 --- a/src/api/java/appeng/api/storage/data/IItemContainer.java +++ b/src/api/java/appeng/api/storage/data/IItemContainer.java @@ -28,6 +28,7 @@ import java.util.Collection; import appeng.api.config.FuzzyMode; + /** * Represents a list of items in AE. * @@ -47,13 +48,15 @@ public interface IItemContainer /** * @param i compared item + * * @return a stack equivalent to the stack passed in, but with the correct stack size information, or null if its - * not present + * not present */ - StackType findPrecise(StackType i); + StackType findPrecise( StackType i ); /** * @param input compared item + * * @return a list of relevant fuzzy matched stacks */ Collection findFuzzy( StackType input, FuzzyMode fuzzy ); @@ -62,5 +65,4 @@ public interface IItemContainer * @return true if there are no items in the list */ boolean isEmpty(); - } \ No newline at end of file diff --git a/src/api/java/appeng/api/storage/data/IItemList.java b/src/api/java/appeng/api/storage/data/IItemList.java index 891ce7032..113ad87fa 100644 --- a/src/api/java/appeng/api/storage/data/IItemList.java +++ b/src/api/java/appeng/api/storage/data/IItemList.java @@ -23,8 +23,10 @@ package appeng.api.storage.data; + import java.util.Iterator; + /** * Represents a list of items in AE. * @@ -78,5 +80,4 @@ public interface IItemList extends IItemContainer VALID_COLORS = Arrays.asList( White, Orange, Magenta, LightBlue, Yellow, Lime, Pink, Gray, LightGray, Cyan, Purple, Blue, Brown, Green, Red, Black ); @@ -94,7 +94,8 @@ public enum AEColor */ final public int whiteVariant; - AEColor(String unlocalizedName, int blackHex, int medHex, int whiteHex) { + AEColor( String unlocalizedName, int blackHex, int medHex, int whiteHex ) + { this.unlocalizedName = unlocalizedName; this.blackVariant = blackHex; this.mediumVariant = medHex; @@ -104,7 +105,7 @@ public enum AEColor /** * Logic to see which colors match each other.. special handle for Transparent */ - public boolean matches(AEColor color) + public boolean matches( AEColor color ) { return this == Transparent || color == Transparent || this == color; } diff --git a/src/api/java/appeng/api/util/DimensionalCoord.java b/src/api/java/appeng/api/util/DimensionalCoord.java index a78bc6078..eb4483606 100644 --- a/src/api/java/appeng/api/util/DimensionalCoord.java +++ b/src/api/java/appeng/api/util/DimensionalCoord.java @@ -64,9 +64,10 @@ public class DimensionalCoord extends WorldCoord return new DimensionalCoord( this ); } - public boolean isEqual( DimensionalCoord c ) + @Override + public int hashCode() { - return this.x == c.x && this.y == c.y && this.z == c.z && c.w == this.w; + return super.hashCode() ^ this.dimId; } @Override @@ -75,15 +76,9 @@ public class DimensionalCoord extends WorldCoord return obj instanceof DimensionalCoord && this.isEqual( (DimensionalCoord) obj ); } - @Override - public int hashCode() + public boolean isEqual( DimensionalCoord c ) { - return super.hashCode() ^ this.dimId; - } - - public boolean isInWorld( World world ) - { - return this.w == world; + return this.x == c.x && this.y == c.y && this.z == c.z && c.w == this.w; } @Override @@ -92,6 +87,11 @@ public class DimensionalCoord extends WorldCoord return "dimension=" + this.dimId + ", " + super.toString(); } + public boolean isInWorld( World world ) + { + return this.w == world; + } + public World getWorld() { return this.w; diff --git a/src/api/java/appeng/api/util/IConfigManager.java b/src/api/java/appeng/api/util/IConfigManager.java index 60026335c..52df69458 100644 --- a/src/api/java/appeng/api/util/IConfigManager.java +++ b/src/api/java/appeng/api/util/IConfigManager.java @@ -49,40 +49,41 @@ public interface IConfigManager /** * used to initialize the configuration manager, should be called for all settings. * - * @param settingName name of setting + * @param settingName name of setting * @param defaultValue default value of setting */ - void registerSetting(Settings settingName, Enum defaultValue); + void registerSetting( Settings settingName, Enum defaultValue ); /** * Get Value of a particular setting * * @param settingName name of setting + * * @return value of setting */ - Enum getSetting(Settings settingName); + Enum getSetting( Settings settingName ); /** * Change setting * * @param settingName to be changed setting - * @param newValue new value for setting + * @param newValue new value for setting + * * @return changed setting */ - Enum putSetting(Settings settingName, Enum newValue); + Enum putSetting( Settings settingName, Enum newValue ); /** * write all settings to the NBT Tag so they can be read later. * * @param destination to be written nbt tag */ - void writeToNBT(NBTTagCompound destination); + void writeToNBT( NBTTagCompound destination ); /** * Only works after settings have been registered * * @param src to be read nbt tag */ - void readFromNBT(NBTTagCompound src); - + void readFromNBT( NBTTagCompound src ); } diff --git a/src/api/java/appeng/api/util/IOrientable.java b/src/api/java/appeng/api/util/IOrientable.java index 18c308c0d..4afbe44e8 100644 --- a/src/api/java/appeng/api/util/IOrientable.java +++ b/src/api/java/appeng/api/util/IOrientable.java @@ -23,8 +23,10 @@ package appeng.api.util; + import net.minecraftforge.common.util.ForgeDirection; + /** * Nearly all of AE's Tile Entities implement IOrientable. * @@ -52,9 +54,9 @@ public interface IOrientable /** * Update the orientation + * * @param Forward new forward direction - * @param Up new upwards direction + * @param Up new upwards direction */ - void setOrientation(ForgeDirection Forward, ForgeDirection Up); - + void setOrientation( ForgeDirection Forward, ForgeDirection Up ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/util/WorldCoord.java b/src/api/java/appeng/api/util/WorldCoord.java index 121c7c95e..3f935c044 100644 --- a/src/api/java/appeng/api/util/WorldCoord.java +++ b/src/api/java/appeng/api/util/WorldCoord.java @@ -39,12 +39,16 @@ public class WorldCoord public int y; public int z; - public WorldCoord add( ForgeDirection direction, int length ) + public WorldCoord( TileEntity s ) { - this.x += direction.offsetX * length; - this.y += direction.offsetY * length; - this.z += direction.offsetZ * length; - return this; + this( s.xCoord, s.yCoord, s.zCoord ); + } + + public WorldCoord( int _x, int _y, int _z ) + { + this.x = _x; + this.y = _y; + this.z = _z; } public WorldCoord subtract( ForgeDirection direction, int length ) @@ -87,18 +91,6 @@ public class WorldCoord return this; } - public WorldCoord( int _x, int _y, int _z ) - { - this.x = _x; - this.y = _y; - this.z = _z; - } - - public WorldCoord( TileEntity s ) - { - this( s.xCoord, s.yCoord, s.zCoord ); - } - /** * Will Return NULL if it's at some diagonal! */ @@ -112,22 +104,22 @@ public class WorldCoord int ylen = Math.abs( oy ); int zlen = Math.abs( oz ); - if ( loc.isEqual( this.copy().add( ForgeDirection.EAST, xlen ) ) ) + if( loc.isEqual( this.copy().add( ForgeDirection.EAST, xlen ) ) ) return ForgeDirection.EAST; - if ( loc.isEqual( this.copy().add( ForgeDirection.WEST, xlen ) ) ) + if( loc.isEqual( this.copy().add( ForgeDirection.WEST, xlen ) ) ) return ForgeDirection.WEST; - if ( loc.isEqual( this.copy().add( ForgeDirection.NORTH, zlen ) ) ) + if( loc.isEqual( this.copy().add( ForgeDirection.NORTH, zlen ) ) ) return ForgeDirection.NORTH; - if ( loc.isEqual( this.copy().add( ForgeDirection.SOUTH, zlen ) ) ) + if( loc.isEqual( this.copy().add( ForgeDirection.SOUTH, zlen ) ) ) return ForgeDirection.SOUTH; - if ( loc.isEqual( this.copy().add( ForgeDirection.UP, ylen ) ) ) + if( loc.isEqual( this.copy().add( ForgeDirection.UP, ylen ) ) ) return ForgeDirection.UP; - if ( loc.isEqual( this.copy().add( ForgeDirection.DOWN, ylen ) ) ) + if( loc.isEqual( this.copy().add( ForgeDirection.DOWN, ylen ) ) ) return ForgeDirection.DOWN; return null; @@ -138,11 +130,25 @@ public class WorldCoord return this.x == c.x && this.y == c.y && this.z == c.z; } + public WorldCoord add( ForgeDirection direction, int length ) + { + this.x += direction.offsetX * length; + this.y += direction.offsetY * length; + this.z += direction.offsetZ * length; + return this; + } + public WorldCoord copy() { return new WorldCoord( this.x, this.y, this.z ); } + @Override + public int hashCode() + { + return ( this.y << 24 ) ^ this.x ^ this.z; + } + @Override public boolean equals( Object obj ) { @@ -154,10 +160,4 @@ public class WorldCoord { return "x=" + this.x + ", y=" + this.y + ", z=" + this.z; } - - @Override - public int hashCode() - { - return ( this.y << 24 ) ^ this.x ^ this.z; - } } diff --git a/src/main/java/appeng/block/AEBaseItemBlock.java b/src/main/java/appeng/block/AEBaseItemBlock.java index 435f8b49c..4927e9f48 100644 --- a/src/main/java/appeng/block/AEBaseItemBlock.java +++ b/src/main/java/appeng/block/AEBaseItemBlock.java @@ -18,6 +18,7 @@ package appeng.block; + import java.util.List; import net.minecraft.block.Block; @@ -42,71 +43,78 @@ import appeng.me.helpers.IGridProxyable; import appeng.tile.AEBaseTile; import appeng.util.Platform; + public class AEBaseItemBlock extends ItemBlock { final AEBaseBlock blockType; - public AEBaseItemBlock(Block id) + public AEBaseItemBlock( Block id ) { super( id ); this.blockType = (AEBaseBlock) id; this.hasSubtypes = this.blockType.hasSubtypes; - if ( Platform.isClient() ) + if( Platform.isClient() ) MinecraftForgeClient.registerItemRenderer( this, ItemRenderer.INSTANCE ); } @Override - public int getMetadata(int dmg) + public int getMetadata( int dmg ) { - if ( this.hasSubtypes ) + if( this.hasSubtypes ) return dmg; return 0; } @Override - public String getUnlocalizedName(ItemStack is) - { - return this.blockType.getUnlocalizedName( is ); - } - - @Override - @SideOnly(Side.CLIENT) - @SuppressWarnings("unchecked") - public final void addInformation(ItemStack itemStack, EntityPlayer player, List toolTip, boolean advancedTooltips) + @SideOnly( Side.CLIENT ) + @SuppressWarnings( "unchecked" ) + public final void addInformation( ItemStack itemStack, EntityPlayer player, List toolTip, boolean advancedTooltips ) { this.addCheckedInformation( itemStack, player, toolTip, advancedTooltips ); } - @SideOnly(Side.CLIENT) - public void addCheckedInformation(ItemStack itemStack, EntityPlayer player, List toolTip, boolean advancedToolTips) + @SideOnly( Side.CLIENT ) + public void addCheckedInformation( ItemStack itemStack, EntityPlayer player, List toolTip, boolean advancedToolTips ) { this.blockType.addInformation( itemStack, player, toolTip, advancedToolTips ); } @Override - public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World w, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata) + public boolean isBookEnchantable( ItemStack itemstack1, ItemStack itemstack2 ) + { + return false; + } + + @Override + public String getUnlocalizedName( ItemStack is ) + { + return this.blockType.getUnlocalizedName( is ); + } + + @Override + public boolean placeBlockAt( ItemStack stack, EntityPlayer player, World w, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata ) { ForgeDirection up = ForgeDirection.UNKNOWN; ForgeDirection forward = ForgeDirection.UNKNOWN; IOrientable ori = null; - if ( this.blockType.hasBlockTileEntity() ) + if( this.blockType.hasBlockTileEntity() ) { - if ( this.blockType instanceof BlockLightDetector ) + if( this.blockType instanceof BlockLightDetector ) { up = ForgeDirection.getOrientation( side ); - if ( up == ForgeDirection.UP || up == ForgeDirection.DOWN ) + if( up == ForgeDirection.UP || up == ForgeDirection.DOWN ) forward = ForgeDirection.SOUTH; else forward = ForgeDirection.UP; } - else if ( this.blockType instanceof BlockWireless || this.blockType instanceof BlockSkyCompass ) + else if( this.blockType instanceof BlockWireless || this.blockType instanceof BlockSkyCompass ) { forward = ForgeDirection.getOrientation( side ); - if ( forward == ForgeDirection.UP || forward == ForgeDirection.DOWN ) + if( forward == ForgeDirection.UP || forward == ForgeDirection.DOWN ) up = ForgeDirection.SOUTH; else up = ForgeDirection.UP; @@ -115,31 +123,31 @@ public class AEBaseItemBlock extends ItemBlock { up = ForgeDirection.UP; - byte rotation = (byte) (MathHelper.floor_double( (player.rotationYaw * 4F) / 360F + 2.5D ) & 3); + byte rotation = (byte) ( MathHelper.floor_double( ( player.rotationYaw * 4F ) / 360F + 2.5D ) & 3 ); - switch (rotation) + switch( rotation ) { - default: - case 0: - forward = ForgeDirection.SOUTH; - break; - case 1: - forward = ForgeDirection.WEST; - break; - case 2: - forward = ForgeDirection.NORTH; - break; - case 3: - forward = ForgeDirection.EAST; - break; + default: + case 0: + forward = ForgeDirection.SOUTH; + break; + case 1: + forward = ForgeDirection.WEST; + break; + case 2: + forward = ForgeDirection.NORTH; + break; + case 3: + forward = ForgeDirection.EAST; + break; } - if ( player.rotationPitch > 65 ) + if( player.rotationPitch > 65 ) { up = forward.getOpposite(); forward = ForgeDirection.UP; } - else if ( player.rotationPitch < -65 ) + else if( player.rotationPitch < -65 ) { up = forward.getOpposite(); forward = ForgeDirection.DOWN; @@ -147,45 +155,45 @@ public class AEBaseItemBlock extends ItemBlock } } - if ( this.blockType instanceof IOrientableBlock ) + if( this.blockType instanceof IOrientableBlock ) { - ori = ((IOrientableBlock) this.blockType).getOrientable( w, x, y, z ); + ori = ( (IOrientableBlock) this.blockType ).getOrientable( w, x, y, z ); up = ForgeDirection.getOrientation( side ); forward = ForgeDirection.SOUTH; - if ( up.offsetY == 0 ) + if( up.offsetY == 0 ) forward = ForgeDirection.UP; ori.setOrientation( forward, up ); } - if ( !this.blockType.isValidOrientation( w, x, y, z, forward, up ) ) + if( !this.blockType.isValidOrientation( w, x, y, z, forward, up ) ) return false; - if ( super.placeBlockAt( stack, player, w, x, y, z, side, hitX, hitY, hitZ, metadata ) ) + if( super.placeBlockAt( stack, player, w, x, y, z, side, hitX, hitY, hitZ, metadata ) ) { - if ( this.blockType.hasBlockTileEntity() && !(this.blockType instanceof BlockLightDetector) ) + if( this.blockType.hasBlockTileEntity() && !( this.blockType instanceof BlockLightDetector ) ) { AEBaseTile tile = this.blockType.getTileEntity( w, x, y, z ); ori = tile; - if ( tile == null ) + if( tile == null ) return true; - if ( ori.canBeRotated() && !this.blockType.hasCustomRotation() ) + if( ori.canBeRotated() && !this.blockType.hasCustomRotation() ) { - if ( ori.getForward() == null || ori.getUp() == null || // null + if( ori.getForward() == null || ori.getUp() == null || // null tile.getForward() == ForgeDirection.UNKNOWN || ori.getUp() == ForgeDirection.UNKNOWN ) ori.setOrientation( forward, up ); } - if ( tile instanceof IGridProxyable ) + if( tile instanceof IGridProxyable ) { - ((IGridProxyable) tile).getProxy().setOwner( player ); + ( (IGridProxyable) tile ).getProxy().setOwner( player ); } tile.onPlacement( stack, player, side ); } - else if ( this.blockType instanceof IOrientableBlock ) + else if( this.blockType instanceof IOrientableBlock ) { ori.setOrientation( forward, up ); } @@ -194,11 +202,4 @@ public class AEBaseItemBlock extends ItemBlock } return false; } - - @Override - public boolean isBookEnchantable(ItemStack itemstack1, ItemStack itemstack2) - { - return false; - } - } diff --git a/src/main/java/appeng/block/AEBaseItemBlockChargeable.java b/src/main/java/appeng/block/AEBaseItemBlockChargeable.java index 9d06bb1e0..32b3cedf7 100644 --- a/src/main/java/appeng/block/AEBaseItemBlockChargeable.java +++ b/src/main/java/appeng/block/AEBaseItemBlockChargeable.java @@ -38,40 +38,40 @@ import appeng.core.Api; import appeng.core.localization.GuiText; import appeng.util.Platform; + public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEItemPowerStorage { - public AEBaseItemBlockChargeable(Block id) { + public AEBaseItemBlockChargeable( Block id ) + { super( id ); } @Override - @SideOnly(Side.CLIENT) - public void addCheckedInformation(ItemStack itemStack, EntityPlayer player, List toolTip, boolean advancedTooltips) + @SideOnly( Side.CLIENT ) + public void addCheckedInformation( ItemStack itemStack, EntityPlayer player, List toolTip, boolean advancedTooltips ) { NBTTagCompound tag = itemStack.getTagCompound(); double internalCurrentPower = 0; double internalMaxPower = this.getMaxEnergyCapacity(); - if ( tag != null ) + if( tag != null ) { internalCurrentPower = tag.getDouble( "internalCurrentPower" ); } double percent = internalCurrentPower / internalMaxPower; - toolTip.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) - + Platform.gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); - + toolTip.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) + Platform.gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); } private double getMaxEnergyCapacity() { Block blockID = Block.getBlockFromItem( this ); final IBlockDefinition energyCell = Api.INSTANCE.definitions().blocks().energyCell(); - for ( Block block : energyCell.maybeBlock().asSet() ) + for( Block block : energyCell.maybeBlock().asSet() ) { - if ( blockID == block ) + if( blockID == block ) { return 200000; } @@ -84,25 +84,13 @@ public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEIte return 0; } - private double getInternal(ItemStack is) - { - NBTTagCompound nbt = Platform.openNbtData( is ); - return nbt.getDouble( "internalCurrentPower" ); - } - - private void setInternal(ItemStack is, double amt) - { - NBTTagCompound nbt = Platform.openNbtData( is ); - nbt.setDouble( "internalCurrentPower", amt ); - } - @Override - public double injectAEPower(ItemStack is, double amt) + public double injectAEPower( ItemStack is, double amt ) { double internalCurrentPower = this.getInternal( is ); double internalMaxPower = this.getMaxEnergyCapacity(); internalCurrentPower += amt; - if ( internalCurrentPower > internalMaxPower ) + if( internalCurrentPower > internalMaxPower ) { amt = internalCurrentPower - internalMaxPower; internalCurrentPower = internalMaxPower; @@ -114,11 +102,23 @@ public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEIte return 0; } + private double getInternal( ItemStack is ) + { + NBTTagCompound nbt = Platform.openNbtData( is ); + return nbt.getDouble( "internalCurrentPower" ); + } + + private void setInternal( ItemStack is, double amt ) + { + NBTTagCompound nbt = Platform.openNbtData( is ); + nbt.setDouble( "internalCurrentPower", amt ); + } + @Override - public double extractAEPower(ItemStack is, double amt) + public double extractAEPower( ItemStack is, double amt ) { double internalCurrentPower = this.getInternal( is ); - if ( internalCurrentPower > amt ) + if( internalCurrentPower > amt ) { internalCurrentPower -= amt; this.setInternal( is, internalCurrentPower ); @@ -131,21 +131,20 @@ public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEIte } @Override - public double getAEMaxPower(ItemStack is) + public double getAEMaxPower( ItemStack is ) { return this.getMaxEnergyCapacity(); } @Override - public double getAECurrentPower(ItemStack is) + public double getAECurrentPower( ItemStack is ) { return this.getInternal( is ); } @Override - public AccessRestriction getPowerFlow(ItemStack is) + public AccessRestriction getPowerFlow( ItemStack is ) { return AccessRestriction.WRITE; } - } diff --git a/src/main/java/appeng/block/AEBaseStairBlock.java b/src/main/java/appeng/block/AEBaseStairBlock.java index f809369fb..36b6de717 100644 --- a/src/main/java/appeng/block/AEBaseStairBlock.java +++ b/src/main/java/appeng/block/AEBaseStairBlock.java @@ -21,11 +21,11 @@ package appeng.block; import java.util.EnumSet; -import com.google.common.base.Optional; - import net.minecraft.block.Block; import net.minecraft.block.BlockStairs; +import com.google.common.base.Optional; + import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; @@ -40,7 +40,7 @@ public abstract class AEBaseStairBlock extends BlockStairs implements IAEFeature { super( block, meta ); - this.features = new StairBlockFeatureHandler( features, this, Optional. absent() ); + this.features = new StairBlockFeatureHandler( features, this, Optional.absent() ); this.setBlockName( block.getUnlocalizedName() ); this.setLightOpacity( 0 ); diff --git a/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java b/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java index 1309b4a16..3ece46589 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java @@ -48,18 +48,24 @@ public class BlockCraftingMonitor extends BlockCraftingUnit this.setTileEntity( TileCraftingMonitorTile.class ); } + @Override + protected Class getRenderer() + { + return RenderBlockCraftingCPUMonitor.class; + } + @Override public IIcon getIcon( int direction, int metadata ) { - if ( direction != ForgeDirection.SOUTH.ordinal() ) + if( direction != ForgeDirection.SOUTH.ordinal() ) { - for ( Block craftingUnitBlock : AEApi.instance().definitions().blocks().craftingUnit().maybeBlock().asSet() ) + for( Block craftingUnitBlock : AEApi.instance().definitions().blocks().craftingUnit().maybeBlock().asSet() ) { return craftingUnitBlock.getIcon( direction, metadata ); } } - switch ( metadata ) + switch( metadata ) { default: case 0: @@ -69,12 +75,6 @@ public class BlockCraftingMonitor extends BlockCraftingUnit } } - @Override - protected Class getRenderer() - { - return RenderBlockCraftingCPUMonitor.class; - } - @Override @SideOnly( Side.CLIENT ) public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) diff --git a/src/main/java/appeng/block/crafting/BlockCraftingStorage.java b/src/main/java/appeng/block/crafting/BlockCraftingStorage.java index 31ad00f60..0ec7694ba 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingStorage.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingStorage.java @@ -18,6 +18,7 @@ package appeng.block.crafting; + import java.util.List; import net.minecraft.creativetab.CreativeTabs; @@ -31,6 +32,7 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.crafting.TileCraftingStorageTile; + public class BlockCraftingStorage extends BlockCraftingUnit { public BlockCraftingStorage() @@ -47,54 +49,54 @@ public class BlockCraftingStorage extends BlockCraftingUnit } @Override - public String getUnlocalizedName(ItemStack is) + public IIcon getIcon( int direction, int metadata ) { - if ( is.getItemDamage() == 1 ) - return "tile.appliedenergistics2.BlockCraftingStorage4k"; - - if ( is.getItemDamage() == 2 ) - return "tile.appliedenergistics2.BlockCraftingStorage16k"; - - if ( is.getItemDamage() == 3 ) - return "tile.appliedenergistics2.BlockCraftingStorage64k"; - - return this.getItemUnlocalizedName( is ); - } - - @Override - public IIcon getIcon(int direction, int metadata) - { - switch (metadata & (~4)) + switch( metadata & ( ~4 ) ) { - default: + default: - case 0: - return super.getIcon( 0, 0 ); - case 1: - return ExtraBlockTextures.BlockCraftingStorage4k.getIcon(); - case 2: - return ExtraBlockTextures.BlockCraftingStorage16k.getIcon(); - case 3: - return ExtraBlockTextures.BlockCraftingStorage64k.getIcon(); + case 0: + return super.getIcon( 0, 0 ); + case 1: + return ExtraBlockTextures.BlockCraftingStorage4k.getIcon(); + case 2: + return ExtraBlockTextures.BlockCraftingStorage16k.getIcon(); + case 3: + return ExtraBlockTextures.BlockCraftingStorage64k.getIcon(); - case FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingStorage1kFit.getIcon(); - case 1 | FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingStorage4kFit.getIcon(); - case 2 | FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingStorage16kFit.getIcon(); - case 3 | FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingStorage64kFit.getIcon(); + case FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingStorage1kFit.getIcon(); + case 1 | FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingStorage4kFit.getIcon(); + case 2 | FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingStorage16kFit.getIcon(); + case 3 | FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingStorage64kFit.getIcon(); } } @Override - @SideOnly(Side.CLIENT) - public void getCheckedSubBlocks(Item item, CreativeTabs tabs, List itemStacks) + @SideOnly( Side.CLIENT ) + public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) { itemStacks.add( new ItemStack( this, 1, 0 ) ); itemStacks.add( new ItemStack( this, 1, 1 ) ); itemStacks.add( new ItemStack( this, 1, 2 ) ); itemStacks.add( new ItemStack( this, 1, 3 ) ); } + + @Override + public String getUnlocalizedName( ItemStack is ) + { + if( is.getItemDamage() == 1 ) + return "tile.appliedenergistics2.BlockCraftingStorage4k"; + + if( is.getItemDamage() == 2 ) + return "tile.appliedenergistics2.BlockCraftingStorage16k"; + + if( is.getItemDamage() == 3 ) + return "tile.appliedenergistics2.BlockCraftingStorage64k"; + + return this.getItemUnlocalizedName( is ); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingUnit.java b/src/main/java/appeng/block/crafting/BlockCraftingUnit.java index 78c347dcd..f3e600547 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingUnit.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingUnit.java @@ -18,6 +18,7 @@ package appeng.block.crafting; + import java.util.EnumSet; import java.util.List; @@ -43,18 +44,11 @@ import appeng.core.sync.GuiBridge; import appeng.tile.crafting.TileCraftingTile; import appeng.util.Platform; + public class BlockCraftingUnit extends AEBaseBlock { public static final int FLAG_FORMED = 8; - public BlockCraftingUnit(Class childClass) - { - super( childClass, Material.iron ); - - this.hasSubtypes = true; - this.setFeature( EnumSet.of( AEFeature.CraftingCPU ) ); - } - public BlockCraftingUnit() { this( BlockCraftingUnit.class ); @@ -62,13 +56,44 @@ public class BlockCraftingUnit extends AEBaseBlock this.setTileEntity( TileCraftingTile.class ); } + public BlockCraftingUnit( Class childClass ) + { + super( childClass, Material.iron ); + + this.hasSubtypes = true; + this.setFeature( EnumSet.of( AEFeature.CraftingCPU ) ); + } + @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + protected Class getRenderer() + { + return RenderBlockCraftingCPU.class; + } + + @Override + public IIcon getIcon( int direction, int metadata ) + { + switch( metadata ) + { + default: + case 0: + return super.getIcon( 0, 0 ); + case 1: + return ExtraBlockTextures.BlockCraftingAccelerator.getIcon(); + case FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingUnitFit.getIcon(); + case 1 | FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingAcceleratorFit.getIcon(); + } + } + + @Override + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { TileCraftingTile tg = this.getTileEntity( w, x, y, z ); - if ( tg != null && !p.isSneaking() && tg.isFormed() && tg.isActive() ) + if( tg != null && !p.isSneaking() && tg.isFormed() && tg.isActive() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CRAFTING_CPU ); @@ -79,34 +104,15 @@ public class BlockCraftingUnit extends AEBaseBlock } @Override - public int getDamageValue(World w, int x, int y, int z) + @SideOnly( Side.CLIENT ) + public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) { - int meta = w.getBlockMetadata( x, y, z ); - return this.damageDropped( meta ); + itemStacks.add( new ItemStack( this, 1, 0 ) ); + itemStacks.add( new ItemStack( this, 1, 1 ) ); } @Override - public int damageDropped(int meta) - { - return meta & 3; - } - - @Override - public String getUnlocalizedName(ItemStack is) - { - if ( is.getItemDamage() == 1 ) - return "tile.appliedenergistics2.BlockCraftingAccelerator"; - - return this.getItemUnlocalizedName( is ); - } - - protected String getItemUnlocalizedName(ItemStack is) - { - return super.getUnlocalizedName( is ); - } - - @Override - public void setRenderStateByMeta(int itemDamage) + public void setRenderStateByMeta( int itemDamage ) { IIcon front = this.getIcon( ForgeDirection.SOUTH.ordinal(), itemDamage ); IIcon other = this.getIcon( ForgeDirection.NORTH.ordinal(), itemDamage ); @@ -114,51 +120,47 @@ public class BlockCraftingUnit extends AEBaseBlock } @Override - public IIcon getIcon(int direction, int metadata) - { - switch (metadata) - { - default: - case 0: - return super.getIcon( 0, 0 ); - case 1: - return ExtraBlockTextures.BlockCraftingAccelerator.getIcon(); - case FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingUnitFit.getIcon(); - case 1 | FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingAcceleratorFit.getIcon(); - } - } - - @Override - protected Class getRenderer() - { - return RenderBlockCraftingCPU.class; - } - - @Override - public void breakBlock(World w, int x, int y, int z, Block a, int b) + public void breakBlock( World w, int x, int y, int z, Block a, int b ) { TileCraftingTile cp = this.getTileEntity( w, x, y, z ); - if ( cp != null ) + if( cp != null ) cp.breakCluster(); super.breakBlock( w, x, y, z, a, b ); } @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block junk) + public String getUnlocalizedName( ItemStack is ) + { + if( is.getItemDamage() == 1 ) + return "tile.appliedenergistics2.BlockCraftingAccelerator"; + + return this.getItemUnlocalizedName( is ); + } + + protected String getItemUnlocalizedName( ItemStack is ) + { + return super.getUnlocalizedName( is ); + } + + @Override + public void onNeighborBlockChange( World w, int x, int y, int z, Block junk ) { TileCraftingTile cp = this.getTileEntity( w, x, y, z ); - if ( cp != null ) + if( cp != null ) cp.updateMultiBlock(); } @Override - @SideOnly(Side.CLIENT) - public void getCheckedSubBlocks(Item item, CreativeTabs tabs, List itemStacks) + public int damageDropped( int meta ) { - itemStacks.add( new ItemStack( this, 1, 0 ) ); - itemStacks.add( new ItemStack( this, 1, 1 ) ); + return meta & 3; + } + + @Override + public int getDamageValue( World w, int x, int y, int z ) + { + int meta = w.getBlockMetadata( x, y, z ); + return this.damageDropped( meta ); } } diff --git a/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java b/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java index 6a62bf637..7d0fbc1e2 100644 --- a/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java +++ b/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java @@ -18,6 +18,7 @@ package appeng.block.crafting; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -36,10 +37,14 @@ import appeng.core.sync.GuiBridge; import appeng.tile.crafting.TileMolecularAssembler; import appeng.util.Platform; + public class BlockMolecularAssembler extends AEBaseBlock { - public BlockMolecularAssembler() { + public static boolean booleanAlphaPass = false; + + public BlockMolecularAssembler() + { super( BlockMolecularAssembler.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.MolecularAssembler ) ); this.setTileEntity( TileMolecularAssembler.class ); @@ -47,15 +52,6 @@ public class BlockMolecularAssembler extends AEBaseBlock this.lightOpacity = 1; } - public static boolean booleanAlphaPass = false; - - @Override - public boolean canRenderInPass(int pass) - { - booleanAlphaPass = pass == 1; - return pass == 0 || pass == 1; - } - @Override public int getRenderBlockPass() { @@ -63,17 +59,24 @@ public class BlockMolecularAssembler extends AEBaseBlock } @Override - @SideOnly(Side.CLIENT) + public boolean canRenderInPass( int pass ) + { + booleanAlphaPass = pass == 1; + return pass == 0 || pass == 1; + } + + @Override + @SideOnly( Side.CLIENT ) public Class getRenderer() { return RenderBlockAssembler.class; } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { TileMolecularAssembler tg = this.getTileEntity( w, x, y, z ); - if ( tg != null && !p.isSneaking() ) + if( tg != null && !p.isSneaking() ) { Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_MAC ); return true; diff --git a/src/main/java/appeng/block/crafting/ItemCraftingStorage.java b/src/main/java/appeng/block/crafting/ItemCraftingStorage.java index c40146139..86369f118 100644 --- a/src/main/java/appeng/block/crafting/ItemCraftingStorage.java +++ b/src/main/java/appeng/block/crafting/ItemCraftingStorage.java @@ -18,6 +18,7 @@ package appeng.block.crafting; + import net.minecraft.block.Block; import net.minecraft.item.ItemStack; @@ -26,27 +27,29 @@ import appeng.block.AEBaseItemBlock; import appeng.core.AEConfig; import appeng.core.features.AEFeature; + public class ItemCraftingStorage extends AEBaseItemBlock { - public ItemCraftingStorage(Block id) { + public ItemCraftingStorage( Block id ) + { super( id ); } @Override - public boolean hasContainerItem(ItemStack stack) + public ItemStack getContainerItem( ItemStack itemStack ) { - return AEConfig.instance.isFeatureEnabled( AEFeature.enableDisassemblyCrafting ); - } - - @Override - public ItemStack getContainerItem(ItemStack itemStack) - { - for ( ItemStack stack : AEApi.instance().definitions().blocks().craftingUnit().maybeStack( 1 ).asSet() ) + for( ItemStack stack : AEApi.instance().definitions().blocks().craftingUnit().maybeStack( 1 ).asSet() ) { return stack; } return null; } + + @Override + public boolean hasContainerItem( ItemStack stack ) + { + return AEConfig.instance.isFeatureEnabled( AEFeature.enableDisassemblyCrafting ); + } } diff --git a/src/main/java/appeng/block/grindstone/BlockCrank.java b/src/main/java/appeng/block/grindstone/BlockCrank.java index 933635a4f..ab3111cf7 100644 --- a/src/main/java/appeng/block/grindstone/BlockCrank.java +++ b/src/main/java/appeng/block/grindstone/BlockCrank.java @@ -18,6 +18,7 @@ package appeng.block.grindstone; + import java.util.EnumSet; import net.minecraft.block.Block; @@ -39,10 +40,12 @@ import appeng.core.stats.Stats; import appeng.tile.AEBaseTile; import appeng.tile.grindstone.TileCrank; + public class BlockCrank extends AEBaseBlock { - public BlockCrank() { + public BlockCrank() + { super( BlockCrank.class, Material.wood ); this.setFeature( EnumSet.of( AEFeature.GrindStone ) ); this.setTileEntity( TileCrank.class ); @@ -52,18 +55,24 @@ public class BlockCrank extends AEBaseBlock } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) + public Class getRenderer() { - if ( player instanceof FakePlayer || player == null ) + return RenderBlockCrank.class; + } + + @Override + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) + { + if( player instanceof FakePlayer || player == null ) { - this.dropCrank(w, x, y, z); + this.dropCrank( w, x, y, z ); return true; } AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if ( tile instanceof TileCrank ) + if( tile instanceof TileCrank ) { - if ( ((TileCrank) tile).power() ) + if( ( (TileCrank) tile ).power() ) { Stats.TurnedCranks.addToPlayer( player, 1 ); } @@ -72,42 +81,6 @@ public class BlockCrank extends AEBaseBlock return true; } - @Override - public Class getRenderer() - { - return RenderBlockCrank.class; - } - - private boolean isCrankable( World world, int x, int y, int z, ForgeDirection offset ) - { - TileEntity te = world.getTileEntity( x + offset.offsetX, y + offset.offsetY, z + offset.offsetZ ); - - return te instanceof ICrankable && ( ( ICrankable ) te ).canCrankAttach( offset.getOpposite() ); - } - - private ForgeDirection findCrankable( World world, int x, int y, int z ) - { - for ( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - if ( this.isCrankable( world, x, y, z, dir ) ) - { - return dir; - } - return ForgeDirection.UNKNOWN; - } - - @Override - public boolean canPlaceBlockAt( World world, int x, int y, int z ) - { - return this.findCrankable( world , x, y, z ) != ForgeDirection.UNKNOWN; - } - - @Override - public boolean isValidOrientation( World world, int x, int y, int z, ForgeDirection forward, ForgeDirection up ) - { - TileEntity te = world.getTileEntity( x, y, z ); - return !(te instanceof TileCrank) || this.isCrankable( world, x, y, z, up.getOpposite() ); - } - private void dropCrank( World world, int x, int y, int z ) { world.func_147480_a( x, y, z, true ); // w.destroyBlock( x, y, z, true ); @@ -118,11 +91,11 @@ public class BlockCrank extends AEBaseBlock public void onBlockPlacedBy( World world, int x, int y, int z, EntityLivingBase placer, ItemStack itemStack ) { AEBaseTile tile = this.getTileEntity( world, x, y, z ); - if ( tile != null ) + if( tile != null ) { ForgeDirection mnt = this.findCrankable( world, x, y, z ); ForgeDirection forward = ForgeDirection.UP; - if ( mnt == ForgeDirection.UP || mnt == ForgeDirection.DOWN ) + if( mnt == ForgeDirection.UP || mnt == ForgeDirection.DOWN ) { forward = ForgeDirection.SOUTH; } @@ -135,12 +108,36 @@ public class BlockCrank extends AEBaseBlock } @Override - public void onNeighborBlockChange (World world, int x, int y, int z, Block block ) + public boolean isValidOrientation( World world, int x, int y, int z, ForgeDirection forward, ForgeDirection up ) + { + TileEntity te = world.getTileEntity( x, y, z ); + return !( te instanceof TileCrank ) || this.isCrankable( world, x, y, z, up.getOpposite() ); + } + + private ForgeDirection findCrankable( World world, int x, int y, int z ) + { + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) + if( this.isCrankable( world, x, y, z, dir ) ) + { + return dir; + } + return ForgeDirection.UNKNOWN; + } + + private boolean isCrankable( World world, int x, int y, int z, ForgeDirection offset ) + { + TileEntity te = world.getTileEntity( x + offset.offsetX, y + offset.offsetY, z + offset.offsetZ ); + + return te instanceof ICrankable && ( (ICrankable) te ).canCrankAttach( offset.getOpposite() ); + } + + @Override + public void onNeighborBlockChange( World world, int x, int y, int z, Block block ) { AEBaseTile tile = this.getTileEntity( world, x, y, z ); - if ( tile != null ) + if( tile != null ) { - if ( !this.isCrankable( world, x, y, z, tile.getUp().getOpposite() ) ) + if( !this.isCrankable( world, x, y, z, tile.getUp().getOpposite() ) ) { this.dropCrank( world, x, y, z ); } @@ -151,4 +148,9 @@ public class BlockCrank extends AEBaseBlock } } + @Override + public boolean canPlaceBlockAt( World world, int x, int y, int z ) + { + return this.findCrankable( world, x, y, z ) != ForgeDirection.UNKNOWN; + } } diff --git a/src/main/java/appeng/block/grindstone/BlockGrinder.java b/src/main/java/appeng/block/grindstone/BlockGrinder.java index 4d6dbdbbc..74bd80d63 100644 --- a/src/main/java/appeng/block/grindstone/BlockGrinder.java +++ b/src/main/java/appeng/block/grindstone/BlockGrinder.java @@ -18,6 +18,7 @@ package appeng.block.grindstone; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -31,10 +32,12 @@ import appeng.core.sync.GuiBridge; import appeng.tile.grindstone.TileGrinder; import appeng.util.Platform; + public class BlockGrinder extends AEBaseBlock { - public BlockGrinder() { + public BlockGrinder() + { super( BlockGrinder.class, Material.rock ); this.setFeature( EnumSet.of( AEFeature.GrindStone ) ); this.setTileEntity( TileGrinder.class ); @@ -42,15 +45,14 @@ public class BlockGrinder extends AEBaseBlock } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { TileGrinder tg = this.getTileEntity( w, x, y, z ); - if ( tg != null && !p.isSneaking() ) + if( tg != null && !p.isSneaking() ) { Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_GRINDER ); return true; } return false; } - } diff --git a/src/main/java/appeng/block/misc/BlockCellWorkbench.java b/src/main/java/appeng/block/misc/BlockCellWorkbench.java index fbd00d9e3..a527ab543 100644 --- a/src/main/java/appeng/block/misc/BlockCellWorkbench.java +++ b/src/main/java/appeng/block/misc/BlockCellWorkbench.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -31,29 +32,30 @@ import appeng.core.sync.GuiBridge; import appeng.tile.misc.TileCellWorkbench; import appeng.util.Platform; + public class BlockCellWorkbench extends AEBaseBlock { - public BlockCellWorkbench() { + public BlockCellWorkbench() + { super( BlockCellWorkbench.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.StorageCells ) ); this.setTileEntity( TileCellWorkbench.class ); } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) return false; TileCellWorkbench tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) + if( tg != null ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CELL_WORKBENCH ); return true; } return false; } - } diff --git a/src/main/java/appeng/block/misc/BlockCharger.java b/src/main/java/appeng/block/misc/BlockCharger.java index 3cfcfda80..dafd30ef2 100644 --- a/src/main/java/appeng/block/misc/BlockCharger.java +++ b/src/main/java/appeng/block/misc/BlockCharger.java @@ -48,10 +48,12 @@ import appeng.tile.AEBaseTile; import appeng.tile.misc.TileCharger; import appeng.util.Platform; + public class BlockCharger extends AEBaseBlock implements ICustomCollision { - public BlockCharger() { + public BlockCharger() + { super( BlockCharger.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.Core ) ); this.setTileEntity( TileCharger.class ); @@ -59,24 +61,6 @@ public class BlockCharger extends AEBaseBlock implements ICustomCollision this.isFullSize = this.isOpaque = false; } - @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) - { - if ( player.isSneaking() ) - return false; - - if ( Platform.isServer() ) - { - TileCharger tc = this.getTileEntity( w, x, y, z ); - if ( tc != null ) - { - tc.activate( player ); - } - } - - return true; - } - @Override protected Class getRenderer() { @@ -84,29 +68,47 @@ public class BlockCharger extends AEBaseBlock implements ICustomCollision } @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World w, int x, int y, int z, Random r) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) { - if ( !AEConfig.instance.enableEffects ) + if( player.isSneaking() ) + return false; + + if( Platform.isServer() ) + { + TileCharger tc = this.getTileEntity( w, x, y, z ); + if( tc != null ) + { + tc.activate( player ); + } + } + + return true; + } + + @Override + @SideOnly( Side.CLIENT ) + public void randomDisplayTick( World w, int x, int y, int z, Random r ) + { + if( !AEConfig.instance.enableEffects ) return; - if ( r.nextFloat() < 0.98 ) + if( r.nextFloat() < 0.98 ) return; AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if ( tile instanceof TileCharger ) + if( tile instanceof TileCharger ) { TileCharger tc = (TileCharger) tile; - if ( AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( tc.getStackInSlot( 0 ) ) ) + if( AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( tc.getStackInSlot( 0 ) ) ) { double xOff = 0.0; double yOff = 0.0; double zOff = 0.0; - for (int bolts = 0; bolts < 3; bolts++) + for( int bolts = 0; bolts < 3; bolts++ ) { - if ( CommonHelper.proxy.shouldAddParticles( r ) ) + if( CommonHelper.proxy.shouldAddParticles( r ) ) { LightningFX fx = new LightningFX( w, xOff + 0.5 + x, yOff + 0.5 + y, zOff + 0.5 + z, 0.0D, 0.0D, 0.0D ); Minecraft.getMinecraft().effectRenderer.addEffect( fx ); @@ -117,54 +119,54 @@ public class BlockCharger extends AEBaseBlock implements ICustomCollision } @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { TileCharger tile = this.getTileEntity( w, x, y, z ); - if ( tile != null ) + if( tile != null ) { double twoPixels = 2.0 / 16.0; ForgeDirection up = tile.getUp(); ForgeDirection forward = tile.getForward(); AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( twoPixels, twoPixels, twoPixels, 1.0 - twoPixels, 1.0 - twoPixels, 1.0 - twoPixels ); - if ( up.offsetX != 0 ) + if( up.offsetX != 0 ) { bb.minX = 0; bb.maxX = 1; } - if ( up.offsetY != 0 ) + if( up.offsetY != 0 ) { bb.minY = 0; bb.maxY = 1; } - if ( up.offsetZ != 0 ) + if( up.offsetZ != 0 ) { bb.minZ = 0; bb.maxZ = 1; } - switch (forward) + switch( forward ) { - case DOWN: - bb.maxY = 1; - break; - case UP: - bb.minY = 0; - break; - case NORTH: - bb.maxZ = 1; - break; - case SOUTH: - bb.minZ = 0; - break; - case EAST: - bb.minX = 0; - break; - case WEST: - bb.maxX = 1; - break; - default: - break; + case DOWN: + bb.maxY = 1; + break; + case UP: + bb.minY = 0; + break; + case NORTH: + bb.maxZ = 1; + break; + case SOUTH: + bb.minZ = 0; + break; + case EAST: + bb.minX = 0; + break; + case WEST: + bb.maxX = 1; + break; + default: + break; } return Collections.singletonList( bb ); @@ -173,7 +175,7 @@ public class BlockCharger extends AEBaseBlock implements ICustomCollision } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); } diff --git a/src/main/java/appeng/block/misc/BlockCondenser.java b/src/main/java/appeng/block/misc/BlockCondenser.java index ac5c4e375..84861eebe 100644 --- a/src/main/java/appeng/block/misc/BlockCondenser.java +++ b/src/main/java/appeng/block/misc/BlockCondenser.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -31,32 +32,33 @@ import appeng.core.sync.GuiBridge; import appeng.tile.misc.TileCondenser; import appeng.util.Platform; + public class BlockCondenser extends AEBaseBlock { - public BlockCondenser() { + public BlockCondenser() + { super( BlockCondenser.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.Core ) ); this.setTileEntity( TileCondenser.class ); } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) { - if ( player.isSneaking() ) + if( player.isSneaking() ) return false; - if ( Platform.isServer() ) + if( Platform.isServer() ) { TileCondenser tc = this.getTileEntity( w, x, y, z ); - if ( tc != null && !player.isSneaking() ) + if( tc != null && !player.isSneaking() ) { - Platform.openGUI( player, tc, ForgeDirection.getOrientation(side), GuiBridge.GUI_CONDENSER ); + Platform.openGUI( player, tc, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CONDENSER ); return true; } } return true; } - } diff --git a/src/main/java/appeng/block/misc/BlockInscriber.java b/src/main/java/appeng/block/misc/BlockInscriber.java index ce83bbcdb..ae8b3953d 100644 --- a/src/main/java/appeng/block/misc/BlockInscriber.java +++ b/src/main/java/appeng/block/misc/BlockInscriber.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -33,10 +34,12 @@ import appeng.core.sync.GuiBridge; import appeng.tile.misc.TileInscriber; import appeng.util.Platform; + public class BlockInscriber extends AEBaseBlock { - public BlockInscriber() { + public BlockInscriber() + { super( BlockInscriber.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.Inscriber ) ); this.setTileEntity( TileInscriber.class ); @@ -51,19 +54,18 @@ public class BlockInscriber extends AEBaseBlock } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) return false; TileInscriber tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) + if( tg != null ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_INSCRIBER ); return true; } return false; } - } diff --git a/src/main/java/appeng/block/misc/BlockInterface.java b/src/main/java/appeng/block/misc/BlockInterface.java index 6c4d156cd..b49ff4074 100644 --- a/src/main/java/appeng/block/misc/BlockInterface.java +++ b/src/main/java/appeng/block/misc/BlockInterface.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -34,10 +35,12 @@ import appeng.core.sync.GuiBridge; import appeng.tile.misc.TileInterface; import appeng.util.Platform; + public class BlockInterface extends AEBaseBlock { - public BlockInterface() { + public BlockInterface() + { super( BlockInterface.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.Core ) ); this.setTileEntity( TileInterface.class ); @@ -49,6 +52,22 @@ public class BlockInterface extends AEBaseBlock return RenderBlockInterface.class; } + @Override + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) + { + if( p.isSneaking() ) + return false; + + TileInterface tg = this.getTileEntity( w, x, y, z ); + if( tg != null ) + { + if( Platform.isServer() ) + Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_INTERFACE ); + return true; + } + return false; + } + @Override protected boolean hasCustomRotation() { @@ -56,27 +75,11 @@ public class BlockInterface extends AEBaseBlock } @Override - protected void customRotateBlock(IOrientable rotatable, ForgeDirection axis) + protected void customRotateBlock( IOrientable rotatable, ForgeDirection axis ) { - if ( rotatable instanceof TileInterface ) + if( rotatable instanceof TileInterface ) { - ((TileInterface) rotatable).setSide( axis ); + ( (TileInterface) rotatable ).setSide( axis ); } } - - @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) - { - if ( p.isSneaking() ) - return false; - - TileInterface tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) - { - if ( Platform.isServer() ) - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_INTERFACE ); - return true; - } - return false; - } } diff --git a/src/main/java/appeng/block/misc/BlockLightDetector.java b/src/main/java/appeng/block/misc/BlockLightDetector.java index 873222f1a..fddc8b2f5 100644 --- a/src/main/java/appeng/block/misc/BlockLightDetector.java +++ b/src/main/java/appeng/block/misc/BlockLightDetector.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import java.util.Random; @@ -30,39 +31,40 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.core.features.AEFeature; import appeng.tile.misc.TileLightDetector; + public class BlockLightDetector extends BlockQuartzTorch { - public BlockLightDetector() { + public BlockLightDetector() + { super( BlockLightDetector.class ); this.setFeature( EnumSet.of( AEFeature.LightDetector ) ); this.setTileEntity( TileLightDetector.class ); } @Override - public void onNeighborChange(IBlockAccess world, int x, int y, int z, int tileX, int tileY, int tileZ) + public int isProvidingWeakPower( IBlockAccess w, int x, int y, int z, int side ) { - super.onNeighborChange( world, x, y, z, tileX, tileY, tileZ ); - - TileLightDetector tld = this.getTileEntity( world, x, y, z ); - if ( tld != null ) - tld.updateLight(); - } - - @Override - public int isProvidingWeakPower(IBlockAccess w, int x, int y, int z, int side) - { - if ( w instanceof World && ((TileLightDetector) this.getTileEntity( w, x, y, z )).isReady() ) - return ((World) w).getBlockLightValue( x, y, z ) - 6; + if( w instanceof World && ( (TileLightDetector) this.getTileEntity( w, x, y, z ) ).isReady() ) + return ( (World) w ).getBlockLightValue( x, y, z ) - 6; return 0; } @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World w, int x, int y, int z, Random r) + public void onNeighborChange( IBlockAccess world, int x, int y, int z, int tileX, int tileY, int tileZ ) + { + super.onNeighborChange( world, x, y, z, tileX, tileY, tileZ ); + + TileLightDetector tld = this.getTileEntity( world, x, y, z ); + if( tld != null ) + tld.updateLight(); + } + + @Override + @SideOnly( Side.CLIENT ) + public void randomDisplayTick( World w, int x, int y, int z, Random r ) { // cancel out lightning } - } diff --git a/src/main/java/appeng/block/misc/BlockPaint.java b/src/main/java/appeng/block/misc/BlockPaint.java index 09fe7003e..dadf4ebc7 100644 --- a/src/main/java/appeng/block/misc/BlockPaint.java +++ b/src/main/java/appeng/block/misc/BlockPaint.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import java.util.List; import java.util.Random; @@ -42,10 +43,12 @@ import appeng.core.features.AEFeature; import appeng.tile.misc.TilePaint; import appeng.util.Platform; + public class BlockPaint extends AEBaseBlock { - public BlockPaint() { + public BlockPaint() + { super( BlockPaint.class, new MaterialLiquid( MapColor.airColor ) ); this.setFeature( EnumSet.of( AEFeature.PaintBalls ) ); this.setTileEntity( TilePaint.class ); @@ -61,11 +64,58 @@ public class BlockPaint extends AEBaseBlock } @Override - public int getLightValue(IBlockAccess w, int x, int y, int z) + @SideOnly( Side.CLIENT ) + public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) + { + // do nothing + } + + @Override + public AxisAlignedBB getCollisionBoundingBoxFromPool( World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_ ) + { + return null; + } + + @Override + public boolean canCollideCheck( int p_149678_1_, boolean p_149678_2_ ) + { + return false; + } + + @Override + public void onNeighborBlockChange( World w, int x, int y, int z, Block junk ) { TilePaint tp = this.getTileEntity( w, x, y, z ); - if ( tp != null ) + if( tp != null ) + tp.onNeighborBlockChange(); + } + + @Override + public Item getItemDropped( int p_149650_1_, Random p_149650_2_, int p_149650_3_ ) + { + return null; + } + + @Override + public void dropBlockAsItemWithChance( World p_149690_1_, int p_149690_2_, int p_149690_3_, int p_149690_4_, int p_149690_5_, float p_149690_6_, int p_149690_7_ ) + { + + } + + @Override + public void fillWithRain( World w, int x, int y, int z ) + { + if( Platform.isServer() ) + w.setBlock( x, y, z, Platform.AIR, 0, 3 ); + } + + @Override + public int getLightValue( IBlockAccess w, int x, int y, int z ) + { + TilePaint tp = this.getTileEntity( w, x, y, z ); + + if( tp != null ) { return tp.getLightLevel(); } @@ -74,63 +124,14 @@ public class BlockPaint extends AEBaseBlock } @Override - @SideOnly(Side.CLIENT) - public void getCheckedSubBlocks(Item item, CreativeTabs tabs, List itemStacks) - { - // do nothing - } - - @Override - public void fillWithRain(World w, int x, int y, int z) - { - if ( Platform.isServer() ) - w.setBlock( x, y, z, Platform.AIR, 0, 3 ); - } - - @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block junk) - { - TilePaint tp = this.getTileEntity( w, x, y, z ); - - if ( tp != null ) - tp.onNeighborBlockChange(); - } - - @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_) - { - return null; - } - - @Override - public boolean canCollideCheck(int p_149678_1_, boolean p_149678_2_) - { - return false; - } - - @Override - public void dropBlockAsItemWithChance(World p_149690_1_, int p_149690_2_, int p_149690_3_, int p_149690_4_, int p_149690_5_, float p_149690_6_, - int p_149690_7_) - { - - } - - @Override - public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_) - { - return null; - } - - @Override - public boolean isAir(IBlockAccess world, int x, int y, int z) + public boolean isReplaceable( IBlockAccess world, int x, int y, int z ) { return true; } @Override - public boolean isReplaceable(IBlockAccess world, int x, int y, int z) + public boolean isAir( IBlockAccess world, int x, int y, int z ) { return true; } - } diff --git a/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java b/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java index b2280af91..5985693db 100644 --- a/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java +++ b/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import java.util.Random; @@ -44,10 +45,12 @@ import appeng.helpers.MetaRotation; import appeng.tile.misc.TileQuartzGrowthAccelerator; import appeng.util.Platform; + public class BlockQuartzGrowthAccelerator extends AEBaseBlock implements IOrientableBlock { - public BlockQuartzGrowthAccelerator() { + public BlockQuartzGrowthAccelerator() + { super( BlockQuartzGrowthAccelerator.class, Material.rock ); this.setStepSound( Block.soundTypeMetal ); this.setFeature( EnumSet.of( AEFeature.Core ) ); @@ -61,21 +64,15 @@ public class BlockQuartzGrowthAccelerator extends AEBaseBlock implements IOrient } @Override - public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) + @SideOnly( Side.CLIENT ) + public void randomDisplayTick( World w, int x, int y, int z, Random r ) { - return new MetaRotation( w, x, y, z ); - } - - @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World w, int x, int y, int z, Random r) - { - if ( !AEConfig.instance.enableEffects ) + if( !AEConfig.instance.enableEffects ) return; TileQuartzGrowthAccelerator tileQuartzGrowthAccelerator = this.getTileEntity( w, x, y, z ); - if ( tileQuartzGrowthAccelerator != null && tileQuartzGrowthAccelerator.hasPower && CommonHelper.proxy.shouldAddParticles( r ) ) + if( tileQuartzGrowthAccelerator != null && tileQuartzGrowthAccelerator.hasPower && CommonHelper.proxy.shouldAddParticles( r ) ) { double d0 = r.nextFloat() - 0.5F; double d1 = r.nextFloat() - 0.5F; @@ -95,34 +92,32 @@ public class BlockQuartzGrowthAccelerator extends AEBaseBlock implements IOrient ry += up.offsetY * d0; rz += up.offsetZ * d0; - switch (r.nextInt( 4 )) + switch( r.nextInt( 4 ) ) { - case 0: - dx = 0.6; - dz = d1; - if ( !w.getBlock( x + west.offsetX, y + west.offsetY, z + west.offsetZ ).isAir( w, x + west.offsetX, y + west.offsetY, z + west.offsetZ ) ) - return; - break; - case 1: - dx = d1; - dz += 0.6; - if ( !w.getBlock( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ ).isAir( w, x + forward.offsetX, y + forward.offsetY, - z + forward.offsetZ ) ) - return; - break; - case 2: - dx = d1; - dz = -0.6; - if ( !w.getBlock( x - forward.offsetX, y - forward.offsetY, z - forward.offsetZ ).isAir( w, x - forward.offsetX, y - forward.offsetY, - z - forward.offsetZ ) ) - return; - break; - case 3: - dx = -0.6; - dz = d1; - if ( !w.getBlock( x - west.offsetX, y - west.offsetY, z - west.offsetZ ).isAir( w, x - west.offsetX, y - west.offsetY, z - west.offsetZ ) ) - return; - break; + case 0: + dx = 0.6; + dz = d1; + if( !w.getBlock( x + west.offsetX, y + west.offsetY, z + west.offsetZ ).isAir( w, x + west.offsetX, y + west.offsetY, z + west.offsetZ ) ) + return; + break; + case 1: + dx = d1; + dz += 0.6; + if( !w.getBlock( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ ).isAir( w, x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ ) ) + return; + break; + case 2: + dx = d1; + dz = -0.6; + if( !w.getBlock( x - forward.offsetX, y - forward.offsetY, z - forward.offsetZ ).isAir( w, x - forward.offsetX, y - forward.offsetY, z - forward.offsetZ ) ) + return; + break; + case 3: + dx = -0.6; + dz = d1; + if( !w.getBlock( x - west.offsetX, y - west.offsetY, z - west.offsetZ ).isAir( w, x - west.offsetX, y - west.offsetY, z - west.offsetZ ) ) + return; + break; } rx += dx * west.offsetX; @@ -143,4 +138,10 @@ public class BlockQuartzGrowthAccelerator extends AEBaseBlock implements IOrient { return true; } + + @Override + public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) + { + return new MetaRotation( w, x, y, z ); + } } diff --git a/src/main/java/appeng/block/misc/BlockQuartzTorch.java b/src/main/java/appeng/block/misc/BlockQuartzTorch.java index 70b38f0c1..5377133b4 100644 --- a/src/main/java/appeng/block/misc/BlockQuartzTorch.java +++ b/src/main/java/appeng/block/misc/BlockQuartzTorch.java @@ -48,21 +48,24 @@ import appeng.core.features.AEFeature; import appeng.helpers.ICustomCollision; import appeng.helpers.MetaRotation; + public class BlockQuartzTorch extends AEBaseBlock implements IOrientableBlock, ICustomCollision { - protected BlockQuartzTorch(Class which) { - super( which, Material.circuits ); - this.setLightOpacity( 0 ); - this.isFullSize = this.isOpaque = false; - } - - public BlockQuartzTorch() { + public BlockQuartzTorch() + { this( BlockQuartzTorch.class ); this.setFeature( EnumSet.of( AEFeature.DecorativeLights ) ); this.setLightLevel( 0.9375F ); } + protected BlockQuartzTorch( Class which ) + { + super( which, Material.circuits ); + this.setLightOpacity( 0 ); + this.isFullSize = this.isOpaque = false; + } + @Override protected Class getRenderer() { @@ -70,48 +73,18 @@ public class BlockQuartzTorch extends AEBaseBlock implements IOrientableBlock, I } @Override - public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) + public boolean isValidOrientation( World w, int x, int y, int z, ForgeDirection forward, ForgeDirection up ) { - return new MetaRotation( w, x, y, z ); + return this.canPlaceAt( w, x, y, z, up.getOpposite() ); } - private void dropTorch(World w, int x, int y, int z) - { - w.func_147480_a( x, y, z, true ); - // w.destroyBlock( x, y, z, true ); - w.markBlockForUpdate( x, y, z ); - } - - @Override - public boolean canPlaceBlockAt(World w, int x, int y, int z) - { - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) - if ( this.canPlaceAt( w, x, y, z, dir ) ) - return true; - return false; - } - - private boolean canPlaceAt(World w, int x, int y, int z, ForgeDirection dir) + private boolean canPlaceAt( World w, int x, int y, int z, ForgeDirection dir ) { return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); } @Override - public boolean isValidOrientation(World w, int x, int y, int z, ForgeDirection forward, ForgeDirection up) - { - return this.canPlaceAt( w, x, y, z, up.getOpposite() ); - } - - @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block id) - { - ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - if ( !this.canPlaceAt( w, x, y, z, up.getOpposite() ) ) - this.dropTorch( w, x, y, z ); - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); double xOff = -0.3 * up.offsetX; @@ -121,7 +94,7 @@ public class BlockQuartzTorch extends AEBaseBlock implements IOrientableBlock, I } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) {/* * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * getUp().offsetY; double zOff = -0.15 * * getUp().offsetZ; out.add( AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + (double) y + 0.15, zOff @@ -130,22 +103,22 @@ public class BlockQuartzTorch extends AEBaseBlock implements IOrientableBlock, I } @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World w, int x, int y, int z, Random r) + @SideOnly( Side.CLIENT ) + public void randomDisplayTick( World w, int x, int y, int z, Random r ) { - if ( !AEConfig.instance.enableEffects ) + if( !AEConfig.instance.enableEffects ) return; - if ( r.nextFloat() < 0.98 ) + if( r.nextFloat() < 0.98 ) return; ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); double xOff = -0.3 * up.offsetX; double yOff = -0.3 * up.offsetY; double zOff = -0.3 * up.offsetZ; - for (int bolts = 0; bolts < 3; bolts++) + for( int bolts = 0; bolts < 3; bolts++ ) { - if ( CommonHelper.proxy.shouldAddParticles( r ) ) + if( CommonHelper.proxy.shouldAddParticles( r ) ) { LightningFX fx = new LightningFX( w, xOff + 0.5 + x, yOff + 0.5 + y, zOff + 0.5 + z, 0.0D, 0.0D, 0.0D ); @@ -154,10 +127,39 @@ public class BlockQuartzTorch extends AEBaseBlock implements IOrientableBlock, I } } + @Override + public void onNeighborBlockChange( World w, int x, int y, int z, Block id ) + { + ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); + if( !this.canPlaceAt( w, x, y, z, up.getOpposite() ) ) + this.dropTorch( w, x, y, z ); + } + + private void dropTorch( World w, int x, int y, int z ) + { + w.func_147480_a( x, y, z, true ); + // w.destroyBlock( x, y, z, true ); + w.markBlockForUpdate( x, y, z ); + } + + @Override + public boolean canPlaceBlockAt( World w, int x, int y, int z ) + { + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) + if( this.canPlaceAt( w, x, y, z, dir ) ) + return true; + return false; + } + @Override public boolean usesMetadata() { return true; } + @Override + public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) + { + return new MetaRotation( w, x, y, z ); + } } diff --git a/src/main/java/appeng/block/misc/BlockSecurity.java b/src/main/java/appeng/block/misc/BlockSecurity.java index 6825f07f6..0f2e575ff 100644 --- a/src/main/java/appeng/block/misc/BlockSecurity.java +++ b/src/main/java/appeng/block/misc/BlockSecurity.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -33,10 +34,12 @@ import appeng.core.sync.GuiBridge; import appeng.tile.misc.TileSecurity; import appeng.util.Platform; + public class BlockSecurity extends AEBaseBlock { - public BlockSecurity() { + public BlockSecurity() + { super( BlockSecurity.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.Security ) ); this.setTileEntity( TileSecurity.class ); @@ -49,22 +52,20 @@ public class BlockSecurity extends AEBaseBlock } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) return false; TileSecurity tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) + if( tg != null ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_SECURITY ); return true; - } return false; } - } diff --git a/src/main/java/appeng/block/misc/BlockSkyCompass.java b/src/main/java/appeng/block/misc/BlockSkyCompass.java index 272ba84d8..73361fbc2 100644 --- a/src/main/java/appeng/block/misc/BlockSkyCompass.java +++ b/src/main/java/appeng/block/misc/BlockSkyCompass.java @@ -43,10 +43,12 @@ import appeng.core.features.AEFeature; import appeng.helpers.ICustomCollision; import appeng.tile.misc.TileSkyCompass; + public class BlockSkyCompass extends AEBaseBlock implements ICustomCollision { - public BlockSkyCompass() { + public BlockSkyCompass() + { super( BlockSkyCompass.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.MeteoriteCompass ) ); this.setTileEntity( TileSkyCompass.class ); @@ -54,20 +56,49 @@ public class BlockSkyCompass extends AEBaseBlock implements ICustomCollision this.lightOpacity = 0; } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int direction, int metadata) - { - return Blocks.iron_block.getIcon( direction, metadata ); - } - @Override protected Class getRenderer() { return RenderBlockSkyCompass.class; } - private void dropTorch(World w, int x, int y, int z) + @Override + @SideOnly( Side.CLIENT ) + public IIcon getIcon( int direction, int metadata ) + { + return Blocks.iron_block.getIcon( direction, metadata ); + } + + @Override + public void registerBlockIcons( IIconRegister iconRegistry ) + { + // :P + } + + @Override + public boolean isValidOrientation( World w, int x, int y, int z, ForgeDirection forward, ForgeDirection up ) + { + TileSkyCompass sc = this.getTileEntity( w, x, y, z ); + if( sc != null ) + return false; + return this.canPlaceAt( w, x, y, z, forward.getOpposite() ); + } + + private boolean canPlaceAt( World w, int x, int y, int z, ForgeDirection dir ) + { + return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); + } + + @Override + public void onNeighborBlockChange( World w, int x, int y, int z, Block id ) + { + TileSkyCompass sc = this.getTileEntity( w, x, y, z ); + ForgeDirection up = sc.getForward(); + if( !this.canPlaceAt( w, x, y, z, up.getOpposite() ) ) + this.dropTorch( w, x, y, z ); + } + + private void dropTorch( World w, int x, int y, int z ) { w.func_147480_a( x, y, z, true ); // w.destroyBlock( x, y, z, true ); @@ -75,42 +106,19 @@ public class BlockSkyCompass extends AEBaseBlock implements ICustomCollision } @Override - public boolean canPlaceBlockAt(World w, int x, int y, int z) + public boolean canPlaceBlockAt( World w, int x, int y, int z ) { - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) - if ( this.canPlaceAt( w, x, y, z, dir ) ) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) + if( this.canPlaceAt( w, x, y, z, dir ) ) return true; return false; } - private boolean canPlaceAt(World w, int x, int y, int z, ForgeDirection dir) - { - return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); - } - @Override - public boolean isValidOrientation(World w, int x, int y, int z, ForgeDirection forward, ForgeDirection up) - { - TileSkyCompass sc = this.getTileEntity( w, x, y, z ); - if ( sc != null ) - return false; - return this.canPlaceAt( w, x, y, z, forward.getOpposite() ); - } - - @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block id) - { - TileSkyCompass sc = this.getTileEntity( w, x, y, z ); - ForgeDirection up = sc.getForward(); - if ( !this.canPlaceAt( w, x, y, z, up.getOpposite() ) ) - this.dropTorch( w, x, y, z ); - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { TileSkyCompass tile = this.getTileEntity( w, x, y, z ); - if ( tile != null ) + if( tile != null ) { ForgeDirection forward = tile.getForward(); @@ -121,46 +129,46 @@ public class BlockSkyCompass extends AEBaseBlock implements ICustomCollision double maxY = 1; double maxZ = 1; - switch (forward) + switch( forward ) { - case DOWN: - minZ = minX = 5.0 / 16.0; - maxZ = maxX = 11.0 / 16.0; - maxY = 1.0; - minY = 14.0 / 16.0; - break; - case EAST: - minZ = minY = 5.0 / 16.0; - maxZ = maxY = 11.0 / 16.0; - maxX = 2.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 5.0 / 16.0; - maxY = maxX = 11.0 / 16.0; - maxZ = 1.0; - minZ = 14.0 / 16.0; - break; - case SOUTH: - minY = minX = 5.0 / 16.0; - maxY = maxX = 11.0 / 16.0; - maxZ = 2.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 5.0 / 16.0; - maxZ = maxX = 11.0 / 16.0; - maxY = 2.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 5.0 / 16.0; - maxZ = maxY = 11.0 / 16.0; - maxX = 1.0; - minX = 14.0 / 16.0; - break; - default: - break; + case DOWN: + minZ = minX = 5.0 / 16.0; + maxZ = maxX = 11.0 / 16.0; + maxY = 1.0; + minY = 14.0 / 16.0; + break; + case EAST: + minZ = minY = 5.0 / 16.0; + maxZ = maxY = 11.0 / 16.0; + maxX = 2.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 5.0 / 16.0; + maxY = maxX = 11.0 / 16.0; + maxZ = 1.0; + minZ = 14.0 / 16.0; + break; + case SOUTH: + minY = minX = 5.0 / 16.0; + maxY = maxX = 11.0 / 16.0; + maxZ = 2.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 5.0 / 16.0; + maxZ = maxX = 11.0 / 16.0; + maxY = 2.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 5.0 / 16.0; + maxZ = maxY = 11.0 / 16.0; + maxX = 1.0; + minX = 14.0 / 16.0; + break; + default: + break; } return Collections.singletonList( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); @@ -169,14 +177,8 @@ public class BlockSkyCompass extends AEBaseBlock implements ICustomCollision } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { } - - @Override - public void registerBlockIcons(IIconRegister iconRegistry) - { - // :P - } } diff --git a/src/main/java/appeng/block/misc/BlockTinyTNT.java b/src/main/java/appeng/block/misc/BlockTinyTNT.java index d87a8e901..090737199 100644 --- a/src/main/java/appeng/block/misc/BlockTinyTNT.java +++ b/src/main/java/appeng/block/misc/BlockTinyTNT.java @@ -52,10 +52,12 @@ import appeng.entity.EntityTinyTNTPrimed; import appeng.helpers.ICustomCollision; import appeng.hooks.DispenserBehaviorTinyTNT; + public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision { - public BlockTinyTNT() { + public BlockTinyTNT() + { super( BlockTinyTNT.class, Material.tnt ); this.setFeature( EnumSet.of( AEFeature.TinyTNT ) ); this.setLightOpacity( 1 ); @@ -67,6 +69,12 @@ public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision EntityRegistry.registerModEntity( EntityTinyTNTPrimed.class, "EntityTinyTNTPrimed", EntityIds.TINY_TNT, AppEng.instance, 16, 4, true ); } + @Override + protected Class getRenderer() + { + return RenderTinyTNT.class; + } + @Override public void postInit() { @@ -75,64 +83,15 @@ public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision } @Override - protected Class getRenderer() - { - return RenderTinyTNT.class; - } - - @Override - public void registerBlockIcons(IIconRegister iconRegistry) - { - // no images required. - } - - @Override - public IIcon getIcon(int direction, int metadata) + public IIcon getIcon( int direction, int metadata ) { return new FullIcon( Blocks.tnt.getIcon( direction, metadata ) ); } @Override - public void onEntityCollidedWithBlock(World w, int x, int y, int z, Entity entity) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) { - if ( entity instanceof EntityArrow && !w.isRemote ) - { - EntityArrow entityarrow = (EntityArrow) entity; - - if ( entityarrow.isBurning() ) - { - this.startFuse( w, x, y, z, entityarrow.shootingEntity instanceof EntityLivingBase ? (EntityLivingBase) entityarrow.shootingEntity : null ); - w.setBlockToAir( x, y, z ); - } - } - } - - @Override - public void onBlockAdded(World w, int x, int y, int z) - { - super.onBlockAdded( w, x, y, z ); - - if ( w.isBlockIndirectlyGettingPowered( x, y, z ) ) - { - this.startFuse( w, x, y, z, null ); - w.setBlockToAir( x, y, z ); - } - } - - @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block id) - { - if ( w.isBlockIndirectlyGettingPowered( x, y, z ) ) - { - this.startFuse( w, x, y, z, null ); - w.setBlockToAir( x, y, z ); - } - } - - @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) - { - if ( player.getCurrentEquippedItem() != null && player.getCurrentEquippedItem().getItem() == Items.flint_and_steel ) + if( player.getCurrentEquippedItem() != null && player.getCurrentEquippedItem().getItem() == Items.flint_and_steel ) { this.startFuse( w, x, y, z, player ); w.setBlockToAir( x, y, z ); @@ -146,19 +105,14 @@ public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision } @Override - public void onBlockDestroyedByExplosion(World w, int x, int y, int z, Explosion exp) + public void registerBlockIcons( IIconRegister iconRegistry ) { - if ( !w.isRemote ) - { - EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( w, x + 0.5F, y + 0.5F, z + 0.5F, exp.getExplosivePlacedBy() ); - primedTinyTNTEntity.fuse = w.rand.nextInt( primedTinyTNTEntity.fuse / 4 ) + primedTinyTNTEntity.fuse / 8; - w.spawnEntityInWorld( primedTinyTNTEntity ); - } + // no images required. } - public void startFuse(World w, int x, int y, int z, EntityLivingBase igniter) + public void startFuse( World w, int x, int y, int z, EntityLivingBase igniter ) { - if ( !w.isRemote ) + if( !w.isRemote ) { EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( w, x + 0.5F, y + 0.5F, z + 0.5F, igniter ); w.spawnEntityInWorld( primedTinyTNTEntity ); @@ -167,21 +121,68 @@ public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision } @Override - public boolean canDropFromExplosion(Explosion exp) + public void onBlockAdded( World w, int x, int y, int z ) + { + super.onBlockAdded( w, x, y, z ); + + if( w.isBlockIndirectlyGettingPowered( x, y, z ) ) + { + this.startFuse( w, x, y, z, null ); + w.setBlockToAir( x, y, z ); + } + } + + @Override + public void onNeighborBlockChange( World w, int x, int y, int z, Block id ) + { + if( w.isBlockIndirectlyGettingPowered( x, y, z ) ) + { + this.startFuse( w, x, y, z, null ); + w.setBlockToAir( x, y, z ); + } + } + + @Override + public void onBlockDestroyedByExplosion( World w, int x, int y, int z, Explosion exp ) + { + if( !w.isRemote ) + { + EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( w, x + 0.5F, y + 0.5F, z + 0.5F, exp.getExplosivePlacedBy() ); + primedTinyTNTEntity.fuse = w.rand.nextInt( primedTinyTNTEntity.fuse / 4 ) + primedTinyTNTEntity.fuse / 8; + w.spawnEntityInWorld( primedTinyTNTEntity ); + } + } + + @Override + public void onEntityCollidedWithBlock( World w, int x, int y, int z, Entity entity ) + { + if( entity instanceof EntityArrow && !w.isRemote ) + { + EntityArrow entityarrow = (EntityArrow) entity; + + if( entityarrow.isBurning() ) + { + this.startFuse( w, x, y, z, entityarrow.shootingEntity instanceof EntityLivingBase ? (EntityLivingBase) entityarrow.shootingEntity : null ); + w.setBlockToAir( x, y, z ); + } + } + } + + @Override + public boolean canDropFromExplosion( Explosion exp ) { return false; } @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) ); } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { out.add( AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) ); } - } diff --git a/src/main/java/appeng/block/misc/BlockVibrationChamber.java b/src/main/java/appeng/block/misc/BlockVibrationChamber.java index 4cdccfa39..74b45c07c 100644 --- a/src/main/java/appeng/block/misc/BlockVibrationChamber.java +++ b/src/main/java/appeng/block/misc/BlockVibrationChamber.java @@ -18,6 +18,7 @@ package appeng.block.misc; + import java.util.EnumSet; import java.util.Random; @@ -37,10 +38,12 @@ import appeng.tile.AEBaseTile; import appeng.tile.misc.TileVibrationChamber; import appeng.util.Platform; + public class BlockVibrationChamber extends AEBaseBlock { - public BlockVibrationChamber() { + public BlockVibrationChamber() + { super( BlockVibrationChamber.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.PowerGen ) ); this.setTileEntity( TileVibrationChamber.class ); @@ -48,15 +51,29 @@ public class BlockVibrationChamber extends AEBaseBlock } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) + public IIcon getIcon( IBlockAccess w, int x, int y, int z, int s ) { - if ( player.isSneaking() ) + IIcon ico = super.getIcon( w, x, y, z, s ); + TileVibrationChamber tvc = this.getTileEntity( w, x, y, z ); + + if( tvc != null && tvc.isOn && ico == this.getRendererInstance().getTexture( ForgeDirection.SOUTH ) ) + { + return ExtraBlockTextures.BlockVibrationChamberFrontOn.getIcon(); + } + + return ico; + } + + @Override + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) + { + if( player.isSneaking() ) return false; - if ( Platform.isServer() ) + if( Platform.isServer() ) { TileVibrationChamber tc = this.getTileEntity( w, x, y, z ); - if ( tc != null && !player.isSneaking() ) + if( tc != null && !player.isSneaking() ) { Platform.openGUI( player, tc, ForgeDirection.getOrientation( side ), GuiBridge.GUI_VIBRATION_CHAMBER ); return true; @@ -67,30 +84,16 @@ public class BlockVibrationChamber extends AEBaseBlock } @Override - public IIcon getIcon(IBlockAccess w, int x, int y, int z, int s) + public void randomDisplayTick( World w, int x, int y, int z, Random r ) { - IIcon ico = super.getIcon( w, x, y, z, s ); - TileVibrationChamber tvc = this.getTileEntity( w, x, y, z ); - - if ( tvc != null && tvc.isOn && ico == this.getRendererInstance().getTexture( ForgeDirection.SOUTH ) ) - { - return ExtraBlockTextures.BlockVibrationChamberFrontOn.getIcon(); - } - - return ico; - } - - @Override - public void randomDisplayTick(World w, int x, int y, int z, Random r) - { - if ( !AEConfig.instance.enableEffects ) + if( !AEConfig.instance.enableEffects ) return; AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if ( tile instanceof TileVibrationChamber ) + if( tile instanceof TileVibrationChamber ) { TileVibrationChamber tc = (TileVibrationChamber) tile; - if ( tc.isOn ) + if( tc.isOn ) { float f1 = x + 0.5F; float f2 = y + 0.5F; @@ -110,18 +113,17 @@ public class BlockVibrationChamber extends AEBaseBlock float ox = r.nextFloat(); float oy = r.nextFloat() * 0.2f; - f1 += up.offsetX * (-0.3 + oy); - f2 += up.offsetY * (-0.3 + oy); - f3 += up.offsetZ * (-0.3 + oy); + f1 += up.offsetX * ( -0.3 + oy ); + f2 += up.offsetY * ( -0.3 + oy ); + f3 += up.offsetZ * ( -0.3 + oy ); - f1 += west_x * (0.3 * ox - 0.15); - f2 += west_y * (0.3 * ox - 0.15); - f3 += west_z * (0.3 * ox - 0.15); + f1 += west_x * ( 0.3 * ox - 0.15 ); + f2 += west_y * ( 0.3 * ox - 0.15 ); + f3 += west_z * ( 0.3 * ox - 0.15 ); w.spawnParticle( "smoke", f1, f2, f3, 0.0D, 0.0D, 0.0D ); w.spawnParticle( "flame", f1, f2, f3, 0.0D, 0.0D, 0.0D ); } } } - } diff --git a/src/main/java/appeng/block/networking/BlockCableBus.java b/src/main/java/appeng/block/networking/BlockCableBus.java index a7bd72cfd..334789a16 100644 --- a/src/main/java/appeng/block/networking/BlockCableBus.java +++ b/src/main/java/appeng/block/networking/BlockCableBus.java @@ -18,6 +18,7 @@ package appeng.block.networking; + import java.util.EnumSet; import java.util.List; import java.util.Random; @@ -74,29 +75,22 @@ import appeng.transformer.annotations.Integration.Interface; import appeng.transformer.annotations.Integration.Method; import appeng.util.Platform; -@Interface(iface = "powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection", iname = "MFR") + +@Interface( iface = "powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection", iname = "MFR" ) public class BlockCableBus extends AEBaseBlock implements IRedNetConnection { private static final ICableBusContainer NULL_CABLE_BUS = new NullCableBusContainer(); static public Class noTesrTile; static public Class tesrTile; + /** + * Immibis MB Support. + */ + boolean ImmibisMicroblocks_TransformableBlockMarker = true; + int myColorMultiplier = 0xffffff; - @Override - public T getTileEntity(IBlockAccess w, int x, int y, int z) + public BlockCableBus() { - TileEntity te = w.getTileEntity( x, y, z ); - - if ( noTesrTile.isInstance( te ) ) - return (T) te; - - if ( tesrTile != null && tesrTile.isInstance( te ) ) - return (T) te; - - return null; - } - - public BlockCableBus() { super( BlockCableBus.class, AEGlassMaterial.INSTANCE ); this.setFeature( EnumSet.of( AEFeature.Core ) ); this.setLightOpacity( 0 ); @@ -104,240 +98,41 @@ public class BlockCableBus extends AEBaseBlock implements IRedNetConnection } @Override - public int getRenderBlockPass() - { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) - return 1; - return 0; - } - - @Override - @SideOnly(Side.CLIENT) - public boolean addHitEffects(World world, MovingObjectPosition target, EffectRenderer effectRenderer) - { - Object object = this.cb( world, target.blockX, target.blockY, target.blockZ ); - if ( object instanceof IPartHost ) - { - IPartHost host = (IPartHost) object; - - for (ForgeDirection side : ForgeDirection.values()) - { - IPart p = host.getPart( side ); - IIcon ico = this.getIcon( p ); - - if ( ico == null ) - continue; - - byte b0 = (byte) (Platform.getRandomInt() % 2 == 0 ? 1 : 0); - - for (int i1 = 0; i1 < b0; ++i1) - { - for (int j1 = 0; j1 < b0; ++j1) - { - for (int k1 = 0; k1 < b0; ++k1) - { - double d0 = target.blockX + (i1 + 0.5D) / b0; - double d1 = target.blockY + (j1 + 0.5D) / b0; - double d2 = target.blockZ + (k1 + 0.5D) / b0; - - double dd0 = target.hitVec.xCoord; - double dd1 = target.hitVec.yCoord; - double dd2 = target.hitVec.zCoord; - EntityDiggingFX fx = (new EntityDiggingFX( world, dd0, dd1, dd2, d0 - target.blockX - 0.5D, d1 - target.blockY - - 0.5D, d2 - target.blockZ - 0.5D, this, 0 )).applyColourMultiplier( target.blockX, target.blockY, target.blockZ ); - - fx.setParticleIcon( ico ); - - effectRenderer.addEffect( fx ); - } - } - } - } - } - - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public boolean addDestroyEffects(World world, int x, int y, int z, int meta, EffectRenderer effectRenderer) - { - Object object = this.cb( world, x, y, z ); - if ( object instanceof IPartHost ) - { - IPartHost host = (IPartHost) object; - - for (ForgeDirection side : ForgeDirection.values()) - { - IPart p = host.getPart( side ); - IIcon ico = this.getIcon( p ); - - if ( ico == null ) - continue; - - byte b0 = 3; - - for (int i1 = 0; i1 < b0; ++i1) - { - for (int j1 = 0; j1 < b0; ++j1) - { - for (int k1 = 0; k1 < b0; ++k1) - { - double d0 = x + (i1 + 0.5D) / b0; - double d1 = y + (j1 + 0.5D) / b0; - double d2 = z + (k1 + 0.5D) / b0; - EntityDiggingFX fx = (new EntityDiggingFX( world, d0, d1, d2, d0 - x - 0.5D, d1 - y - 0.5D, d2 - z - - 0.5D, this, meta )).applyColourMultiplier( x, y, z ); - - fx.setParticleIcon( ico ); - - effectRenderer.addEffect( fx ); - } - } - } - } - } - - return true; - } - - private IIcon getIcon(IPart p) - { - if ( p == null ) - return null; - - try - { - IIcon ico = p.getBreakingTexture(); - if ( ico != null ) - return ico; - } - catch (Throwable t) - { - // nothing. - } - - ItemStack is = p.getItemStack( PartItemStack.Network ); - if ( is == null || is.getItem() == null ) - return null; - - return is.getItem().getIcon( is, 0 ); - } - - @Override - public boolean canRenderInPass(int pass) - { - BusRenderHelper.INSTANCE.setPass( pass ); - - if ( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) - return true; - - return pass == 0; - } - - @Override - public boolean isLadder(IBlockAccess world, int x, int y, int z, EntityLivingBase entity) - { - return this.cb( world, x, y, z ).isLadder( entity ); - } - - @Override - public boolean recolourBlock(World world, int x, int y, int z, ForgeDirection side, int colour) - { - return this.recolourBlock( world, x, y, z, side, colour, null ); - } - - public boolean recolourBlock(World world, int x, int y, int z, ForgeDirection side, int colour, EntityPlayer who) - { - try - { - return this.cb( world, x, y, z ).recolourBlock( side, AEColor.values()[colour], who ); - } - catch (Throwable ignored) - { - } - return false; - } - - @Override - public void randomDisplayTick(World world, int x, int y, int z, Random r) + public void randomDisplayTick( World world, int x, int y, int z, Random r ) { this.cb( world, x, y, z ).randomDisplayTick( world, x, y, z, r ); } @Override - public int getLightValue(IBlockAccess world, int x, int y, int z) + public void onNeighborBlockChange( World w, int x, int y, int z, Block meh ) { - Block block = world.getBlock( x, y, z ); - if ( block != null && block != this ) - { - return block.getLightValue( world, x, y, z ); - } - if ( block == null ) - return 0; - return this.cb( world, x, y, z ).getLightValue(); + this.cb( w, x, y, z ).onNeighborChanged(); } @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) + public Item getItemDropped( int i, Random r, int k ) { - Vec3 v3 = target.hitVec.addVector( -x, -y, -z ); - SelectedPart sp = this.cb( world, x, y, z ).selectPart( v3 ); - - if ( sp.part != null ) - return sp.part.getItemStack( PartItemStack.Pick ); - else if ( sp.facade != null ) - return sp.facade.getItemStack(); - return null; } @Override - public boolean isReplaceable(IBlockAccess world, int x, int y, int z) + public int getRenderBlockPass() { - return this.cb( world, x, y, z ).isEmpty(); - } - - @SuppressWarnings("deprecation") - @Override - public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) - { - if ( player.capabilities.isCreativeMode ) - { - AEBaseTile tile = this.getTileEntity( world, x, y, z ); - if ( tile != null ) - tile.disableDrops(); - // maybe ray trace? - } - return super.removedByPlayer( world, player, x, y, z ); + if( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) + return 1; + return 0; } @Override - public IIcon getIcon(IBlockAccess w, int x, int y, int z, int s) + public int colorMultiplier( IBlockAccess p_149720_1_, int p_149720_2_, int p_149720_3_, int p_149720_4_ ) { - return this.getIcon( s, 0 ); + return this.myColorMultiplier; } @Override - public IIcon getIcon(int direction, int metadata) + public int isProvidingWeakPower( IBlockAccess w, int x, int y, int z, int side ) { - IIcon i = super.getIcon( direction, metadata ); - if ( i != null ) - return i; - - return ExtraBlockTextures.BlockQuartzGlassB.getIcon(); - } - - @Override - protected Class getRenderer() - { - return RendererCableBus.class; - } - - @Override - public void registerBlockIcons(IIconRegister iconRegistry) - { - + return this.cb( w, x, y, z ).isProvidingWeakPower( ForgeDirection.getOrientation( side ).getOpposite() ); } @Override @@ -347,85 +142,316 @@ public class BlockCableBus extends AEBaseBlock implements IRedNetConnection } @Override - public boolean isSideSolid(IBlockAccess w, int x, int y, int z, ForgeDirection side) - { - return this.cb( w, x, y, z ).isSolidOnSide( side ); - } - - @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block meh) - { - this.cb( w, x, y, z ).onNeighborChanged(); - } - - @Override - public void onNeighborChange(IBlockAccess w, int x, int y, int z, int tileX, int tileY, int tileZ) - { - if ( Platform.isServer() ) - this.cb( w, x, y, z ).onNeighborChanged(); - } - - @Override - public Item getItemDropped(int i, Random r, int k) - { - return null; - } - - @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) - { - return this.cb( w, x, y, z ).activate( player, Vec3.createVectorHelper( hitX, hitY, hitZ ) ); - } - - @Override - public void onEntityCollidedWithBlock(World w, int x, int y, int z, Entity e) + public void onEntityCollidedWithBlock( World w, int x, int y, int z, Entity e ) { this.cb( w, x, y, z ).onEntityCollision( e ); } @Override - public boolean canConnectRedstone(IBlockAccess w, int x, int y, int z, int side) - { - switch (side) - { - case -1: - case 4: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ); - case 0: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.NORTH ) ); - case 1: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.EAST ) ); - case 2: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.SOUTH ) ); - case 3: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.WEST ) ); - } - return false; - } - - @Override - public int isProvidingWeakPower(IBlockAccess w, int x, int y, int z, int side) - { - return this.cb( w, x, y, z ).isProvidingWeakPower( ForgeDirection.getOrientation( side ).getOpposite() ); - } - - @Override - public int isProvidingStrongPower(IBlockAccess w, int x, int y, int z, int side) + public int isProvidingStrongPower( IBlockAccess w, int x, int y, int z, int side ) { return this.cb( w, x, y, z ).isProvidingStrongPower( ForgeDirection.getOrientation( side ).getOpposite() ); } @Override - @SideOnly(Side.CLIENT) - public void getCheckedSubBlocks(Item item, CreativeTabs tabs, List itemStacks) + public int getLightValue( IBlockAccess world, int x, int y, int z ) + { + Block block = world.getBlock( x, y, z ); + if( block != null && block != this ) + { + return block.getLightValue( world, x, y, z ); + } + if( block == null ) + return 0; + return this.cb( world, x, y, z ).getLightValue(); + } + + @Override + public boolean isLadder( IBlockAccess world, int x, int y, int z, EntityLivingBase entity ) + { + return this.cb( world, x, y, z ).isLadder( entity ); + } + + @Override + public boolean isSideSolid( IBlockAccess w, int x, int y, int z, ForgeDirection side ) + { + return this.cb( w, x, y, z ).isSolidOnSide( side ); + } + + @Override + public boolean isReplaceable( IBlockAccess world, int x, int y, int z ) + { + return this.cb( world, x, y, z ).isEmpty(); + } + + @SuppressWarnings( "deprecation" ) + @Override + public boolean removedByPlayer( World world, EntityPlayer player, int x, int y, int z ) + { + if( player.capabilities.isCreativeMode ) + { + AEBaseTile tile = this.getTileEntity( world, x, y, z ); + if( tile != null ) + tile.disableDrops(); + // maybe ray trace? + } + return super.removedByPlayer( world, player, x, y, z ); + } + + @Override + public boolean canConnectRedstone( IBlockAccess w, int x, int y, int z, int side ) + { + switch( side ) + { + case -1: + case 4: + return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ); + case 0: + return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.NORTH ) ); + case 1: + return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.EAST ) ); + case 2: + return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.SOUTH ) ); + case 3: + return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.WEST ) ); + } + return false; + } + + @Override + public boolean canRenderInPass( int pass ) + { + BusRenderHelper.INSTANCE.setPass( pass ); + + if( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) + return true; + + return pass == 0; + } + + @Override + public ItemStack getPickBlock( MovingObjectPosition target, World world, int x, int y, int z ) + { + Vec3 v3 = target.hitVec.addVector( -x, -y, -z ); + SelectedPart sp = this.cb( world, x, y, z ).selectPart( v3 ); + + if( sp.part != null ) + return sp.part.getItemStack( PartItemStack.Pick ); + else if( sp.facade != null ) + return sp.facade.getItemStack(); + + return null; + } + + @Override + @SideOnly( Side.CLIENT ) + public boolean addHitEffects( World world, MovingObjectPosition target, EffectRenderer effectRenderer ) + { + Object object = this.cb( world, target.blockX, target.blockY, target.blockZ ); + if( object instanceof IPartHost ) + { + IPartHost host = (IPartHost) object; + + for( ForgeDirection side : ForgeDirection.values() ) + { + IPart p = host.getPart( side ); + IIcon ico = this.getIcon( p ); + + if( ico == null ) + continue; + + byte b0 = (byte) ( Platform.getRandomInt() % 2 == 0 ? 1 : 0 ); + + for( int i1 = 0; i1 < b0; ++i1 ) + { + for( int j1 = 0; j1 < b0; ++j1 ) + { + for( int k1 = 0; k1 < b0; ++k1 ) + { + double d0 = target.blockX + ( i1 + 0.5D ) / b0; + double d1 = target.blockY + ( j1 + 0.5D ) / b0; + double d2 = target.blockZ + ( k1 + 0.5D ) / b0; + + double dd0 = target.hitVec.xCoord; + double dd1 = target.hitVec.yCoord; + double dd2 = target.hitVec.zCoord; + EntityDiggingFX fx = ( new EntityDiggingFX( world, dd0, dd1, dd2, d0 - target.blockX - 0.5D, d1 - target.blockY - 0.5D, d2 - target.blockZ - 0.5D, this, 0 ) ).applyColourMultiplier( target.blockX, target.blockY, target.blockZ ); + + fx.setParticleIcon( ico ); + + effectRenderer.addEffect( fx ); + } + } + } + } + } + + return true; + } + + @Override + @SideOnly( Side.CLIENT ) + public boolean addDestroyEffects( World world, int x, int y, int z, int meta, EffectRenderer effectRenderer ) + { + Object object = this.cb( world, x, y, z ); + if( object instanceof IPartHost ) + { + IPartHost host = (IPartHost) object; + + for( ForgeDirection side : ForgeDirection.values() ) + { + IPart p = host.getPart( side ); + IIcon ico = this.getIcon( p ); + + if( ico == null ) + continue; + + byte b0 = 3; + + for( int i1 = 0; i1 < b0; ++i1 ) + { + for( int j1 = 0; j1 < b0; ++j1 ) + { + for( int k1 = 0; k1 < b0; ++k1 ) + { + double d0 = x + ( i1 + 0.5D ) / b0; + double d1 = y + ( j1 + 0.5D ) / b0; + double d2 = z + ( k1 + 0.5D ) / b0; + EntityDiggingFX fx = ( new EntityDiggingFX( world, d0, d1, d2, d0 - x - 0.5D, d1 - y - 0.5D, d2 - z - 0.5D, this, meta ) ).applyColourMultiplier( x, y, z ); + + fx.setParticleIcon( ico ); + + effectRenderer.addEffect( fx ); + } + } + } + } + } + + return true; + } + + @Override + public void onNeighborChange( IBlockAccess w, int x, int y, int z, int tileX, int tileY, int tileZ ) + { + if( Platform.isServer() ) + this.cb( w, x, y, z ).onNeighborChanged(); + } + + private IIcon getIcon( IPart p ) + { + if( p == null ) + return null; + + try + { + IIcon ico = p.getBreakingTexture(); + if( ico != null ) + return ico; + } + catch( Throwable t ) + { + // nothing. + } + + ItemStack is = p.getItemStack( PartItemStack.Network ); + if( is == null || is.getItem() == null ) + return null; + + return is.getItem().getIcon( is, 0 ); + } + + private ICableBusContainer cb( IBlockAccess w, int x, int y, int z ) + { + TileEntity te = w.getTileEntity( x, y, z ); + ICableBusContainer out = null; + + if( te instanceof TileCableBus ) + out = ( (TileCableBus) te ).cb; + + else if( AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) + out = ( (IFMP) AppEng.instance.getIntegration( IntegrationType.FMP ) ).getCableContainer( te ); + + return out == null ? NULL_CABLE_BUS : out; + } + + @Override + protected Class getRenderer() + { + return RendererCableBus.class; + } + + @Override + public IIcon getIcon( IBlockAccess w, int x, int y, int z, int s ) + { + return this.getIcon( s, 0 ); + } + + @Override + public IIcon getIcon( int direction, int metadata ) + { + IIcon i = super.getIcon( direction, metadata ); + if( i != null ) + return i; + + return ExtraBlockTextures.BlockQuartzGlassB.getIcon(); + } + + @Override + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) + { + return this.cb( w, x, y, z ).activate( player, Vec3.createVectorHelper( hitX, hitY, hitZ ) ); + } + + @Override + public void registerBlockIcons( IIconRegister iconRegistry ) + { + + } + + @Override + public boolean recolourBlock( World world, int x, int y, int z, ForgeDirection side, int colour ) + { + return this.recolourBlock( world, x, y, z, side, colour, null ); + } + + public boolean recolourBlock( World world, int x, int y, int z, ForgeDirection side, int colour, EntityPlayer who ) + { + try + { + return this.cb( world, x, y, z ).recolourBlock( side, AEColor.values()[colour], who ); + } + catch( Throwable ignored ) + { + } + return false; + } + + @Override + @SideOnly( Side.CLIENT ) + public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) { // do nothing } + @Override + public T getTileEntity( IBlockAccess w, int x, int y, int z ) + { + TileEntity te = w.getTileEntity( x, y, z ); + + if( noTesrTile.isInstance( te ) ) + return (T) te; + + if( tesrTile != null && tesrTile.isInstance( te ) ) + return (T) te; + + return null; + } + public void setupTile() { this.setTileEntity( noTesrTile = Api.INSTANCE.getPartHelper().getCombinedInstance( TileCableBus.class.getName() ) ); - if ( Platform.isClient() ) + if( Platform.isClient() ) { tesrTile = Api.INSTANCE.getPartHelper().getCombinedInstance( TileCableBusTESR.class.getName() ); GameRegistry.registerTileEntity( tesrTile, "ClientOnly_TESR_CableBus" ); @@ -433,43 +459,15 @@ public class BlockCableBus extends AEBaseBlock implements IRedNetConnection } } - private ICableBusContainer cb(IBlockAccess w, int x, int y, int z) - { - TileEntity te = w.getTileEntity( x, y, z ); - ICableBusContainer out = null; - - if ( te instanceof TileCableBus ) - out = ((TileCableBus) te).cb; - - else if ( AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) - out = ((IFMP) AppEng.instance.getIntegration( IntegrationType.FMP )).getCableContainer( te ); - - return out == null ? NULL_CABLE_BUS : out; - } - - /** - * Immibis MB Support. - */ - boolean ImmibisMicroblocks_TransformableBlockMarker = true; - @Override - @Method(iname = "MFR") - public RedNetConnectionType getConnectionType(World world, int x, int y, int z, ForgeDirection side) + @Method( iname = "MFR" ) + public RedNetConnectionType getConnectionType( World world, int x, int y, int z, ForgeDirection side ) { return this.cb( world, x, y, z ).canConnectRedstone( EnumSet.allOf( ForgeDirection.class ) ) ? RedNetConnectionType.CableSingle : RedNetConnectionType.None; } - int myColorMultiplier = 0xffffff; - - public void setRenderColor(int color) + public void setRenderColor( int color ) { this.myColorMultiplier = color; } - - @Override - public int colorMultiplier(IBlockAccess p_149720_1_, int p_149720_2_, int p_149720_3_, int p_149720_4_) - { - return this.myColorMultiplier; - } - } diff --git a/src/main/java/appeng/block/networking/BlockController.java b/src/main/java/appeng/block/networking/BlockController.java index 02e4c51ed..edbe8541a 100644 --- a/src/main/java/appeng/block/networking/BlockController.java +++ b/src/main/java/appeng/block/networking/BlockController.java @@ -18,6 +18,7 @@ package appeng.block.networking; + import java.util.EnumSet; import net.minecraft.block.Block; @@ -30,10 +31,12 @@ import appeng.client.render.blocks.RenderBlockController; import appeng.core.features.AEFeature; import appeng.tile.networking.TileController; + public class BlockController extends AEBaseBlock { - public BlockController() { + public BlockController() + { super( BlockController.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.Channels ) ); this.setTileEntity( TileController.class ); @@ -41,10 +44,10 @@ public class BlockController extends AEBaseBlock } @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block id_junk) + public void onNeighborBlockChange( World w, int x, int y, int z, Block id_junk ) { TileController tc = this.getTileEntity( w, x, y, z ); - if ( tc != null ) + if( tc != null ) tc.onNeighborChange( false ); } @@ -53,5 +56,4 @@ public class BlockController extends AEBaseBlock { return RenderBlockController.class; } - } diff --git a/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java b/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java index 4679f4a7f..ab8ce7cdf 100644 --- a/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java @@ -18,6 +18,7 @@ package appeng.block.networking; + import java.util.EnumSet; import appeng.block.AEBaseBlock; @@ -25,13 +26,14 @@ import appeng.core.features.AEFeature; import appeng.helpers.AEGlassMaterial; import appeng.tile.networking.TileCreativeEnergyCell; + public class BlockCreativeEnergyCell extends AEBaseBlock { - public BlockCreativeEnergyCell() { + public BlockCreativeEnergyCell() + { super( BlockCreativeEnergyCell.class, AEGlassMaterial.INSTANCE ); this.setFeature( EnumSet.of( AEFeature.Creative ) ); this.setTileEntity( TileCreativeEnergyCell.class ); } - } diff --git a/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java b/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java index d35cf29d6..b20ec314c 100644 --- a/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java @@ -18,6 +18,7 @@ package appeng.block.networking; + import java.util.EnumSet; import net.minecraft.util.IIcon; @@ -26,45 +27,45 @@ import appeng.client.texture.ExtraBlockTextures; import appeng.core.features.AEFeature; import appeng.tile.networking.TileDenseEnergyCell; + public class BlockDenseEnergyCell extends BlockEnergyCell { - @Override - public double getMaxPower() + public BlockDenseEnergyCell() { - return 200000.0 * 8.0; - } - - public BlockDenseEnergyCell() { super( BlockDenseEnergyCell.class ); this.setFeature( EnumSet.of( AEFeature.DenseEnergyCells ) ); this.setTileEntity( TileDenseEnergyCell.class ); } @Override - public IIcon getIcon(int direction, int metadata) + public IIcon getIcon( int direction, int metadata ) { - switch (metadata) + switch( metadata ) { - case 0: - return ExtraBlockTextures.MEDenseEnergyCell0.getIcon(); - case 1: - return ExtraBlockTextures.MEDenseEnergyCell1.getIcon(); - case 2: - return ExtraBlockTextures.MEDenseEnergyCell2.getIcon(); - case 3: - return ExtraBlockTextures.MEDenseEnergyCell3.getIcon(); - case 4: - return ExtraBlockTextures.MEDenseEnergyCell4.getIcon(); - case 5: - return ExtraBlockTextures.MEDenseEnergyCell5.getIcon(); - case 6: - return ExtraBlockTextures.MEDenseEnergyCell6.getIcon(); - case 7: - return ExtraBlockTextures.MEDenseEnergyCell7.getIcon(); - + case 0: + return ExtraBlockTextures.MEDenseEnergyCell0.getIcon(); + case 1: + return ExtraBlockTextures.MEDenseEnergyCell1.getIcon(); + case 2: + return ExtraBlockTextures.MEDenseEnergyCell2.getIcon(); + case 3: + return ExtraBlockTextures.MEDenseEnergyCell3.getIcon(); + case 4: + return ExtraBlockTextures.MEDenseEnergyCell4.getIcon(); + case 5: + return ExtraBlockTextures.MEDenseEnergyCell5.getIcon(); + case 6: + return ExtraBlockTextures.MEDenseEnergyCell6.getIcon(); + case 7: + return ExtraBlockTextures.MEDenseEnergyCell7.getIcon(); } return super.getIcon( direction, metadata ); } + @Override + public double getMaxPower() + { + return 200000.0 * 8.0; + } } diff --git a/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java b/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java index bbbbf1bcb..5cad1291c 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java +++ b/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java @@ -18,6 +18,7 @@ package appeng.block.networking; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -26,13 +27,14 @@ import appeng.block.AEBaseBlock; import appeng.core.features.AEFeature; import appeng.tile.networking.TileEnergyAcceptor; + public class BlockEnergyAcceptor extends AEBaseBlock { - public BlockEnergyAcceptor() { + public BlockEnergyAcceptor() + { super( BlockEnergyAcceptor.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.Core ) ); this.setTileEntity( TileEnergyAcceptor.class ); } - } diff --git a/src/main/java/appeng/block/networking/BlockEnergyCell.java b/src/main/java/appeng/block/networking/BlockEnergyCell.java index 2d3d5d291..ab1c9a803 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockEnergyCell.java @@ -18,6 +18,7 @@ package appeng.block.networking; + import java.util.EnumSet; import java.util.List; @@ -41,27 +42,56 @@ import appeng.helpers.AEGlassMaterial; import appeng.tile.networking.TileEnergyCell; import appeng.util.Platform; + public class BlockEnergyCell extends AEBaseBlock { - public double getMaxPower() + public BlockEnergyCell() { - return 200000.0; - } - - public BlockEnergyCell(Class c) { - super( c, AEGlassMaterial.INSTANCE ); - } - - public BlockEnergyCell() { this( BlockEnergyCell.class ); this.setFeature( EnumSet.of( AEFeature.Core ) ); this.setTileEntity( TileEnergyCell.class ); } + public BlockEnergyCell( Class c ) + { + super( c, AEGlassMaterial.INSTANCE ); + } + @Override - @SideOnly(Side.CLIENT) - public void getCheckedSubBlocks(Item item, CreativeTabs tabs, List itemStacks) + protected Class getRenderer() + { + return RenderBlockEnergyCube.class; + } + + @Override + public IIcon getIcon( int direction, int metadata ) + { + switch( metadata ) + { + case 0: + return ExtraBlockTextures.MEEnergyCell0.getIcon(); + case 1: + return ExtraBlockTextures.MEEnergyCell1.getIcon(); + case 2: + return ExtraBlockTextures.MEEnergyCell2.getIcon(); + case 3: + return ExtraBlockTextures.MEEnergyCell3.getIcon(); + case 4: + return ExtraBlockTextures.MEEnergyCell4.getIcon(); + case 5: + return ExtraBlockTextures.MEEnergyCell5.getIcon(); + case 6: + return ExtraBlockTextures.MEEnergyCell6.getIcon(); + case 7: + return ExtraBlockTextures.MEEnergyCell7.getIcon(); + } + return super.getIcon( direction, metadata ); + } + + @Override + @SideOnly( Side.CLIENT ) + public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) { super.getCheckedSubBlocks( item, tabs, itemStacks ); @@ -73,36 +103,9 @@ public class BlockEnergyCell extends AEBaseBlock itemStacks.add( charged ); } - @Override - protected Class getRenderer() + public double getMaxPower() { - return RenderBlockEnergyCube.class; - } - - @Override - public IIcon getIcon(int direction, int metadata) - { - switch (metadata) - { - case 0: - return ExtraBlockTextures.MEEnergyCell0.getIcon(); - case 1: - return ExtraBlockTextures.MEEnergyCell1.getIcon(); - case 2: - return ExtraBlockTextures.MEEnergyCell2.getIcon(); - case 3: - return ExtraBlockTextures.MEEnergyCell3.getIcon(); - case 4: - return ExtraBlockTextures.MEEnergyCell4.getIcon(); - case 5: - return ExtraBlockTextures.MEEnergyCell5.getIcon(); - case 6: - return ExtraBlockTextures.MEEnergyCell6.getIcon(); - case 7: - return ExtraBlockTextures.MEEnergyCell7.getIcon(); - - } - return super.getIcon( direction, metadata ); + return 200000.0; } @Override @@ -110,5 +113,4 @@ public class BlockEnergyCell extends AEBaseBlock { return AEBaseItemBlockChargeable.class; } - } diff --git a/src/main/java/appeng/block/networking/BlockWireless.java b/src/main/java/appeng/block/networking/BlockWireless.java index 89ff1db75..42205b0b7 100644 --- a/src/main/java/appeng/block/networking/BlockWireless.java +++ b/src/main/java/appeng/block/networking/BlockWireless.java @@ -39,10 +39,12 @@ import appeng.helpers.ICustomCollision; import appeng.tile.networking.TileWireless; import appeng.util.Platform; + public class BlockWireless extends AEBaseBlock implements ICustomCollision { - public BlockWireless() { + public BlockWireless() + { super( BlockWireless.class, AEGlassMaterial.INSTANCE ); this.setFeature( EnumSet.of( AEFeature.Core, AEFeature.WirelessAccessTerminal ) ); this.setTileEntity( TileWireless.class ); @@ -58,10 +60,26 @@ public class BlockWireless extends AEBaseBlock implements ICustomCollision } @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) + { + if( p.isSneaking() ) + return false; + + TileWireless tg = this.getTileEntity( w, x, y, z ); + if( tg != null ) + { + if( Platform.isServer() ) + Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_WIRELESS ); + return true; + } + return false; + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { TileWireless tile = this.getTileEntity( w, x, y, z ); - if ( tile != null ) + if( tile != null ) { ForgeDirection forward = tile.getForward(); @@ -72,46 +90,46 @@ public class BlockWireless extends AEBaseBlock implements ICustomCollision double maxY = 1; double maxZ = 1; - switch (forward) + switch( forward ) { - case DOWN: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 1.0; - minY = 5.0 / 16.0; - break; - case EAST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 11.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 1.0; - minZ = 5.0 / 16.0; - break; - case SOUTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 11.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 11.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 1.0; - minX = 5.0 / 16.0; - break; - default: - break; + case DOWN: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 1.0; + minY = 5.0 / 16.0; + break; + case EAST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 11.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 1.0; + minZ = 5.0 / 16.0; + break; + case SOUTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 11.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 11.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 1.0; + minX = 5.0 / 16.0; + break; + default: + break; } return Collections.singletonList( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); @@ -120,10 +138,10 @@ public class BlockWireless extends AEBaseBlock implements ICustomCollision } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { TileWireless tile = this.getTileEntity( w, x, y, z ); - if ( tile != null ) + if( tile != null ) { ForgeDirection forward = tile.getForward(); @@ -134,46 +152,46 @@ public class BlockWireless extends AEBaseBlock implements ICustomCollision double maxY = 1; double maxZ = 1; - switch (forward) + switch( forward ) { - case DOWN: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 1.0; - minY = 5.0 / 16.0; - break; - case EAST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 11.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 1.0; - minZ = 5.0 / 16.0; - break; - case SOUTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 11.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 11.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 1.0; - minX = 5.0 / 16.0; - break; - default: - break; + case DOWN: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 1.0; + minY = 5.0 / 16.0; + break; + case EAST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 11.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 1.0; + minZ = 5.0 / 16.0; + break; + case SOUTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 11.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 11.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 1.0; + minX = 5.0 / 16.0; + break; + default: + break; } out.add( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); @@ -181,21 +199,4 @@ public class BlockWireless extends AEBaseBlock implements ICustomCollision else out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); } - - @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) - { - if ( p.isSneaking() ) - return false; - - TileWireless tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) - { - if ( Platform.isServer() ) - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_WIRELESS ); - return true; - } - return false; - } - } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java b/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java index 079c07fba..b1cc2aca5 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java @@ -46,10 +46,12 @@ import appeng.helpers.ICustomCollision; import appeng.tile.qnb.TileQuantumBridge; import appeng.util.Platform; + public class BlockQuantumLinkChamber extends AEBaseBlock implements ICustomCollision { - public BlockQuantumLinkChamber() { + public BlockQuantumLinkChamber() + { super( BlockQuantumLinkChamber.class, AEGlassMaterial.INSTANCE ); this.setFeature( EnumSet.of( AEFeature.QuantumNetworkBridge ) ); this.setTileEntity( TileQuantumBridge.class ); @@ -60,38 +62,28 @@ public class BlockQuantumLinkChamber extends AEBaseBlock implements ICustomColli } @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World w, int bx, int by, int bz, Random r) + @SideOnly( Side.CLIENT ) + public void randomDisplayTick( World w, int bx, int by, int bz, Random r ) { TileQuantumBridge bridge = this.getTileEntity( w, bx, by, bz ); - if ( bridge != null ) + if( bridge != null ) { - if ( bridge.hasQES() ) + if( bridge.hasQES() ) { - if ( CommonHelper.proxy.shouldAddParticles( r ) ) + if( CommonHelper.proxy.shouldAddParticles( r ) ) CommonHelper.proxy.spawnEffect( EffectType.Energy, w, bx + 0.5, by + 0.5, bz + 0.5, null ); } } } @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block pointlessNumber) + public void onNeighborBlockChange( World w, int x, int y, int z, Block pointlessNumber ) { TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if ( bridge != null ) + if( bridge != null ) bridge.neighborUpdate(); } - @Override - public void breakBlock(World w, int x, int y, int z, Block a, int b) - { - TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if ( bridge != null ) - bridge.breakCluster(); - - super.breakBlock( w, x, y, z, a, b ); - } - @Override protected Class getRenderer() { @@ -99,15 +91,15 @@ public class BlockQuantumLinkChamber extends AEBaseBlock implements ICustomColli } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) return false; TileQuantumBridge tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) + if( tg != null ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_QNB ); return true; } @@ -115,17 +107,26 @@ public class BlockQuantumLinkChamber extends AEBaseBlock implements ICustomColli } @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public void breakBlock( World w, int x, int y, int z, Block a, int b ) + { + TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); + if( bridge != null ) + bridge.breakCluster(); + + super.breakBlock( w, x, y, z, a, b ); + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { double OnePx = 2.0 / 16.0; return Collections.singletonList( AxisAlignedBB.getBoundingBox( OnePx, OnePx, OnePx, 1.0 - OnePx, 1.0 - OnePx, 1.0 - OnePx ) ); } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { double OnePx = 2.0 / 16.0; out.add( AxisAlignedBB.getBoundingBox( OnePx, OnePx, OnePx, 1.0 - OnePx, 1.0 - OnePx, 1.0 - OnePx ) ); } - } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumRing.java b/src/main/java/appeng/block/qnb/BlockQuantumRing.java index 9d0b06e0f..b7f330d25 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumRing.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumRing.java @@ -36,10 +36,12 @@ import appeng.core.features.AEFeature; import appeng.helpers.ICustomCollision; import appeng.tile.qnb.TileQuantumBridge; + public class BlockQuantumRing extends AEBaseBlock implements ICustomCollision { - public BlockQuantumRing() { + public BlockQuantumRing() + { super( BlockQuantumRing.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.QuantumNetworkBridge ) ); this.setTileEntity( TileQuantumBridge.class ); @@ -50,23 +52,13 @@ public class BlockQuantumRing extends AEBaseBlock implements ICustomCollision } @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block pointlessNumber) + public void onNeighborBlockChange( World w, int x, int y, int z, Block pointlessNumber ) { TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if ( bridge != null ) + if( bridge != null ) bridge.neighborUpdate(); } - @Override - public void breakBlock(World w, int x, int y, int z, Block a, int b) - { - TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if ( bridge != null ) - bridge.breakCluster(); - - super.breakBlock( w, x, y, z, a, b ); - } - @Override protected Class getRenderer() { @@ -74,15 +66,25 @@ public class BlockQuantumRing extends AEBaseBlock implements ICustomCollision } @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public void breakBlock( World w, int x, int y, int z, Block a, int b ) + { + TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); + if( bridge != null ) + bridge.breakCluster(); + + super.breakBlock( w, x, y, z, a, b ); + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { double OnePx = 2.0 / 16.0; TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if ( bridge != null && bridge.isCorner() ) + if( bridge != null && bridge.isCorner() ) { OnePx = 4.0 / 16.0; } - else if ( bridge != null && bridge.isFormed() ) + else if( bridge != null && bridge.isFormed() ) { OnePx = 1.0 / 16.0; } @@ -90,19 +92,18 @@ public class BlockQuantumRing extends AEBaseBlock implements ICustomCollision } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { double OnePx = 2.0 / 16.0; TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if ( bridge != null && bridge.isCorner() ) + if( bridge != null && bridge.isCorner() ) { OnePx = 4.0 / 16.0; } - else if ( bridge != null && bridge.isFormed() ) + else if( bridge != null && bridge.isFormed() ) { OnePx = 1.0 / 16.0; } out.add( AxisAlignedBB.getBoundingBox( OnePx, OnePx, OnePx, 1.0 - OnePx, 1.0 - OnePx, 1.0 - OnePx ) ); } - } diff --git a/src/main/java/appeng/block/solids/BlockQuartz.java b/src/main/java/appeng/block/solids/BlockQuartz.java index e7c487b0f..cd8575fc5 100644 --- a/src/main/java/appeng/block/solids/BlockQuartz.java +++ b/src/main/java/appeng/block/solids/BlockQuartz.java @@ -18,6 +18,7 @@ package appeng.block.solids; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -25,12 +26,13 @@ import net.minecraft.block.material.Material; import appeng.block.AEDecorativeBlock; import appeng.core.features.AEFeature; + public class BlockQuartz extends AEDecorativeBlock { - public BlockQuartz() { + public BlockQuartz() + { super( BlockQuartz.class, Material.rock ); this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); } - } diff --git a/src/main/java/appeng/block/solids/BlockQuartzChiseled.java b/src/main/java/appeng/block/solids/BlockQuartzChiseled.java index 51a66a719..e19146af4 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzChiseled.java +++ b/src/main/java/appeng/block/solids/BlockQuartzChiseled.java @@ -18,6 +18,7 @@ package appeng.block.solids; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -25,12 +26,13 @@ import net.minecraft.block.material.Material; import appeng.block.AEDecorativeBlock; import appeng.core.features.AEFeature; + public class BlockQuartzChiseled extends AEDecorativeBlock { - public BlockQuartzChiseled() { + public BlockQuartzChiseled() + { super( BlockQuartzChiseled.class, Material.rock ); this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); } - } diff --git a/src/main/java/appeng/block/solids/BlockQuartzGlass.java b/src/main/java/appeng/block/solids/BlockQuartzGlass.java index c0d23f0ef..cf0425efa 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzGlass.java +++ b/src/main/java/appeng/block/solids/BlockQuartzGlass.java @@ -18,6 +18,7 @@ package appeng.block.solids; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -32,37 +33,39 @@ import appeng.client.render.blocks.RenderQuartzGlass; import appeng.core.features.AEFeature; import appeng.helpers.AEGlassMaterial; + public class BlockQuartzGlass extends AEBaseBlock { - public BlockQuartzGlass() { + public BlockQuartzGlass() + { this( BlockQuartzGlass.class ); } - @Override - @SideOnly(Side.CLIENT) - public Class getRenderer() + public BlockQuartzGlass( Class c ) { - return RenderQuartzGlass.class; - } - - @Override - public boolean shouldSideBeRendered(IBlockAccess w, int x, int y, int z, int side) - { - Material mat = w.getBlock( x, y, z ).getMaterial(); - if ( mat == Material.glass || mat == AEGlassMaterial.INSTANCE ) - { - if ( w.getBlock( x, y, z ).getRenderType() == this.getRenderType() ) - return false; - } - return super.shouldSideBeRendered( w, x, y, z, side ); - } - - public BlockQuartzGlass(Class c) { super( c, Material.glass ); this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); this.setLightOpacity( 0 ); this.isOpaque = false; } + @Override + @SideOnly( Side.CLIENT ) + public Class getRenderer() + { + return RenderQuartzGlass.class; + } + + @Override + public boolean shouldSideBeRendered( IBlockAccess w, int x, int y, int z, int side ) + { + Material mat = w.getBlock( x, y, z ).getMaterial(); + if( mat == Material.glass || mat == AEGlassMaterial.INSTANCE ) + { + if( w.getBlock( x, y, z ).getRenderType() == this.getRenderType() ) + return false; + } + return super.shouldSideBeRendered( w, x, y, z, side ); + } } diff --git a/src/main/java/appeng/block/solids/BlockQuartzLamp.java b/src/main/java/appeng/block/solids/BlockQuartzLamp.java index 5cc7d9521..d0d930b46 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzLamp.java +++ b/src/main/java/appeng/block/solids/BlockQuartzLamp.java @@ -18,6 +18,7 @@ package appeng.block.solids; + import java.util.EnumSet; import java.util.Random; @@ -32,10 +33,12 @@ import appeng.core.AEConfig; import appeng.core.CommonHelper; import appeng.core.features.AEFeature; + public class BlockQuartzLamp extends BlockQuartzGlass { - public BlockQuartzLamp() { + public BlockQuartzLamp() + { super( BlockQuartzLamp.class ); this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks, AEFeature.DecorativeLights ) ); this.setLightLevel( 1.0f ); @@ -43,22 +46,21 @@ public class BlockQuartzLamp extends BlockQuartzGlass } @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World w, int x, int y, int z, Random r) + @SideOnly( Side.CLIENT ) + public void randomDisplayTick( World w, int x, int y, int z, Random r ) { - if ( !AEConfig.instance.enableEffects ) + if( !AEConfig.instance.enableEffects ) return; - if ( CommonHelper.proxy.shouldAddParticles( r ) ) + if( CommonHelper.proxy.shouldAddParticles( r ) ) { - double d0 = (r.nextFloat() - 0.5F) * 0.96D; - double d1 = (r.nextFloat() - 0.5F) * 0.96D; - double d2 = (r.nextFloat() - 0.5F) * 0.96D; + double d0 = ( r.nextFloat() - 0.5F ) * 0.96D; + double d1 = ( r.nextFloat() - 0.5F ) * 0.96D; + double d2 = ( r.nextFloat() - 0.5F ) * 0.96D; VibrantFX fx = new VibrantFX( w, 0.5 + x + d0, 0.5 + y + d1, 0.5 + z + d2, 0.0D, 0.0D, 0.0D ); Minecraft.getMinecraft().effectRenderer.addEffect( fx ); } } - } diff --git a/src/main/java/appeng/block/solids/BlockQuartzPillar.java b/src/main/java/appeng/block/solids/BlockQuartzPillar.java index 13ab711d9..39a9b642a 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzPillar.java +++ b/src/main/java/appeng/block/solids/BlockQuartzPillar.java @@ -18,6 +18,7 @@ package appeng.block.solids; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -29,24 +30,25 @@ import appeng.block.AEBaseBlock; import appeng.core.features.AEFeature; import appeng.helpers.MetaRotation; + public class BlockQuartzPillar extends AEBaseBlock implements IOrientableBlock { - public BlockQuartzPillar() { + public BlockQuartzPillar() + { super( BlockQuartzPillar.class, Material.rock ); this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); } - @Override - public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) - { - return new MetaRotation( w, x, y, z ); - } - @Override public boolean usesMetadata() { return true; } + @Override + public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) + { + return new MetaRotation( w, x, y, z ); + } } diff --git a/src/main/java/appeng/block/solids/BlockSkyStone.java b/src/main/java/appeng/block/solids/BlockSkyStone.java index 746ccd645..5002a9e2c 100644 --- a/src/main/java/appeng/block/solids/BlockSkyStone.java +++ b/src/main/java/appeng/block/solids/BlockSkyStone.java @@ -18,6 +18,7 @@ package appeng.block.solids; + import java.util.EnumSet; import java.util.List; @@ -54,36 +55,22 @@ import appeng.integration.IntegrationType; import appeng.integration.abstraction.IRB; import appeng.util.Platform; + @RotatableBlockEnable public class BlockSkyStone extends AEBaseBlock implements IOrientableBlock { - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) IIcon Block; - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) IIcon Brick; - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) IIcon SmallBrick; - @SubscribeEvent - public void breakFaster(PlayerEvent.BreakSpeed Ev) + public BlockSkyStone() { - if ( Ev.block == this && Ev.entityPlayer != null ) - { - ItemStack is = Ev.entityPlayer.inventory.getCurrentItem(); - int level = -1; - - if ( is != null ) - level = is.getItem().getHarvestLevel( is, "pickaxe" ); - - if ( Ev.metadata > 0 || level >= 3 || Ev.originalSpeed > 7.0 ) - Ev.newSpeed /= 0.1; - } - } - - public BlockSkyStone() { super( BlockSkyStone.class, Material.rock ); this.setFeature( EnumSet.of( AEFeature.Core ) ); this.setHardness( 50 ); @@ -93,76 +80,28 @@ public class BlockSkyStone extends AEBaseBlock implements IOrientableBlock MinecraftForge.EVENT_BUS.register( this ); } + @SubscribeEvent + public void breakFaster( PlayerEvent.BreakSpeed Ev ) + { + if( Ev.block == this && Ev.entityPlayer != null ) + { + ItemStack is = Ev.entityPlayer.inventory.getCurrentItem(); + int level = -1; + + if( is != null ) + level = is.getItem().getHarvestLevel( is, "pickaxe" ); + + if( Ev.metadata > 0 || level >= 3 || Ev.originalSpeed > 7.0 ) + Ev.newSpeed /= 0.1; + } + } + @Override - public int damageDropped(int meta) + public int damageDropped( int meta ) { return meta; } - @Override - public String getUnlocalizedName(ItemStack is) - { - if ( is.getItemDamage() == 1 ) - return this.getUnlocalizedName() + ".Block"; - - if ( is.getItemDamage() == 2 ) - return this.getUnlocalizedName() + ".Brick"; - - if ( is.getItemDamage() == 3 ) - return this.getUnlocalizedName() + ".SmallBrick"; - - return this.getUnlocalizedName(); - } - - @Override - public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) - { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.RB ) ) - { - TileEntity te = w.getTileEntity( x, y, z ); - if ( te != null ) - { - IOrientable out = ((IRB) AppEng.instance.getIntegration( IntegrationType.RB )).getOrientable( te ); - if ( out != null ) - return out; - } - } - - if ( w.getBlockMetadata( x, y, z ) == 0 ) - return new LocationRotation( w, x, y, z ); - - return new NullRotation(); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister ir) - { - super.registerBlockIcons( ir ); - this.Block = ir.registerIcon( this.getTextureName() + ".Block" ); - this.Brick = ir.registerIcon( this.getTextureName() + ".Brick" ); - this.SmallBrick = ir.registerIcon( this.getTextureName() + ".SmallBrick" ); - } - - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int direction, int metadata) - { - if ( metadata == 1 ) - return this.Block; - if ( metadata == 2 ) - return this.Brick; - if ( metadata == 3 ) - return this.SmallBrick; - return super.getIcon( direction, metadata ); - } - - @Override - public void setRenderStateByMeta(int metadata) - { - this.getRendererInstance().setTemporaryRenderIcon( this.getIcon( 0, metadata ) ); - } - @Override public ItemStack getPickBlock( MovingObjectPosition target, World world, int x, int y, int z, EntityPlayer player ) { @@ -173,29 +112,10 @@ public class BlockSkyStone extends AEBaseBlock implements IOrientableBlock } @Override - @SideOnly(Side.CLIENT) - public void getCheckedSubBlocks(Item item, CreativeTabs tabs, List itemStacks) - { - super.getCheckedSubBlocks( item, tabs, itemStacks ); - - itemStacks.add( new ItemStack( item, 1, 1 ) ); - itemStacks.add( new ItemStack( item, 1, 2 ) ); - itemStacks.add( new ItemStack( item, 1, 3 ) ); - } - - @Override - public void onBlockAdded(World w, int x, int y, int z) + public void onBlockAdded( World w, int x, int y, int z ) { super.onBlockAdded( w, x, y, z ); - if ( Platform.isServer() ) - WorldSettings.getInstance().getCompass().updateArea( w, x, y, z ); - } - - @Override - public void breakBlock(World w, int x, int y, int z, Block b, int WTF) - { - super.breakBlock( w, x, y, z, b, WTF ); - if ( Platform.isServer() ) + if( Platform.isServer() ) WorldSettings.getInstance().getCompass().updateArea( w, x, y, z ); } @@ -211,4 +131,86 @@ public class BlockSkyStone extends AEBaseBlock implements IOrientableBlock return false; } + @Override + public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) + { + if( AppEng.instance.isIntegrationEnabled( IntegrationType.RB ) ) + { + TileEntity te = w.getTileEntity( x, y, z ); + if( te != null ) + { + IOrientable out = ( (IRB) AppEng.instance.getIntegration( IntegrationType.RB ) ).getOrientable( te ); + if( out != null ) + return out; + } + } + + if( w.getBlockMetadata( x, y, z ) == 0 ) + return new LocationRotation( w, x, y, z ); + + return new NullRotation(); + } + + @Override + public String getUnlocalizedName( ItemStack is ) + { + if( is.getItemDamage() == 1 ) + return this.getUnlocalizedName() + ".Block"; + + if( is.getItemDamage() == 2 ) + return this.getUnlocalizedName() + ".Brick"; + + if( is.getItemDamage() == 3 ) + return this.getUnlocalizedName() + ".SmallBrick"; + + return this.getUnlocalizedName(); + } + + @Override + @SideOnly( Side.CLIENT ) + public void registerBlockIcons( IIconRegister ir ) + { + super.registerBlockIcons( ir ); + this.Block = ir.registerIcon( this.getTextureName() + ".Block" ); + this.Brick = ir.registerIcon( this.getTextureName() + ".Brick" ); + this.SmallBrick = ir.registerIcon( this.getTextureName() + ".SmallBrick" ); + } + + @Override + @SideOnly( Side.CLIENT ) + public IIcon getIcon( int direction, int metadata ) + { + if( metadata == 1 ) + return this.Block; + if( metadata == 2 ) + return this.Brick; + if( metadata == 3 ) + return this.SmallBrick; + return super.getIcon( direction, metadata ); + } + + @Override + public void setRenderStateByMeta( int metadata ) + { + this.getRendererInstance().setTemporaryRenderIcon( this.getIcon( 0, metadata ) ); + } + + @Override + @SideOnly( Side.CLIENT ) + public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) + { + super.getCheckedSubBlocks( item, tabs, itemStacks ); + + itemStacks.add( new ItemStack( item, 1, 1 ) ); + itemStacks.add( new ItemStack( item, 1, 2 ) ); + itemStacks.add( new ItemStack( item, 1, 3 ) ); + } + + @Override + public void breakBlock( World w, int x, int y, int z, Block b, int WTF ) + { + super.breakBlock( w, x, y, z, b, WTF ); + if( Platform.isServer() ) + WorldSettings.getInstance().getCompass().updateArea( w, x, y, z ); + } } diff --git a/src/main/java/appeng/block/solids/OreQuartz.java b/src/main/java/appeng/block/solids/OreQuartz.java index 1ee9670d1..6f4988494 100644 --- a/src/main/java/appeng/block/solids/OreQuartz.java +++ b/src/main/java/appeng/block/solids/OreQuartz.java @@ -21,7 +21,6 @@ package appeng.block.solids; import java.util.EnumSet; import java.util.Random; - import javax.annotation.Nullable; import net.minecraft.block.material.Material; @@ -46,6 +45,11 @@ public class OreQuartz extends AEBaseBlock private int boostBrightnessHigh; private boolean enhanceBrightness; + public OreQuartz() + { + this( OreQuartz.class ); + } + public OreQuartz( Class self ) { super( self, Material.rock ); @@ -57,27 +61,27 @@ public class OreQuartz extends AEBaseBlock this.enhanceBrightness = false; } - @Override - public void postInit() - { - OreDictionary.registerOre( "oreCertusQuartz", new ItemStack( this ) ); - } - @Override protected Class getRenderer() { return RenderQuartzOre.class; } + @Override + public void postInit() + { + OreDictionary.registerOre( "oreCertusQuartz", new ItemStack( this ) ); + } + @Override public int getMixedBrightnessForBlock( IBlockAccess par1iBlockAccess, int par2, int par3, int par4 ) { int j1 = super.getMixedBrightnessForBlock( par1iBlockAccess, par2, par3, par4 ); - if ( this.enhanceBrightness ) + if( this.enhanceBrightness ) { j1 = Math.max( j1 >> 20, j1 >> 4 ); - if ( j1 > 4 ) + if( j1 > 4 ) { j1 += this.boostBrightnessHigh; } @@ -86,55 +90,63 @@ public class OreQuartz extends AEBaseBlock j1 += this.boostBrightnessLow; } - if ( j1 > 15 ) + if( j1 > 15 ) j1 = 15; return j1 << 20 | j1 << 4; } return j1; } - public OreQuartz() - { - this( OreQuartz.class ); - } - - @Nullable - @Override - public Item getItemDropped( int id, Random rand, int meta ) - { - for ( Item crystalItem : AEApi.instance().definitions().materials().certusQuartzCrystal().maybeItem().asSet() ) - { - return crystalItem; - } - - throw new MissingDefinition( "Tried to access certus quartz crystal, even though they are disabled" ); - } - - @Override - public int damageDropped( int id ) - { - for ( ItemStack crystalStack : AEApi.instance().definitions().materials().certusQuartzCrystal().maybeStack( 1 ).asSet() ) - { - return crystalStack.getItemDamage(); - } - - throw new MissingDefinition( "Tried to access certus quartz crystal, even though they are disabled" ); - } - @Override public int quantityDropped( Random rand ) { return 1 + rand.nextInt( 2 ); } + @Nullable + @Override + public Item getItemDropped( int id, Random rand, int meta ) + { + for( Item crystalItem : AEApi.instance().definitions().materials().certusQuartzCrystal().maybeItem().asSet() ) + { + return crystalItem; + } + + throw new MissingDefinition( "Tried to access certus quartz crystal, even though they are disabled" ); + } + + @Override + public void dropBlockAsItemWithChance( World w, int x, int y, int z, int blockID, float something, int meta ) + { + super.dropBlockAsItemWithChance( w, x, y, z, blockID, something, meta ); + + if( this.getItemDropped( blockID, w.rand, meta ) != Item.getItemFromBlock( this ) ) + { + int xp = MathHelper.getRandomIntegerInRange( w.rand, 2, 5 ); + + this.dropXpOnBlockBreak( w, x, y, z, xp ); + } + } + + @Override + public int damageDropped( int id ) + { + for( ItemStack crystalStack : AEApi.instance().definitions().materials().certusQuartzCrystal().maybeStack( 1 ).asSet() ) + { + return crystalStack.getItemDamage(); + } + + throw new MissingDefinition( "Tried to access certus quartz crystal, even though they are disabled" ); + } + @Override public int quantityDroppedWithBonus( int fortune, Random rand ) { - if ( fortune > 0 && Item.getItemFromBlock( this ) != this.getItemDropped( 0, rand, fortune ) ) + if( fortune > 0 && Item.getItemFromBlock( this ) != this.getItemDropped( 0, rand, fortune ) ) { int j = rand.nextInt( fortune + 2 ) - 1; - if ( j < 0 ) + if( j < 0 ) { j = 0; } @@ -147,19 +159,6 @@ public class OreQuartz extends AEBaseBlock } } - @Override - public void dropBlockAsItemWithChance( World w, int x, int y, int z, int blockID, float something, int meta ) - { - super.dropBlockAsItemWithChance( w, x, y, z, blockID, something, meta ); - - if ( this.getItemDropped( blockID, w.rand, meta ) != Item.getItemFromBlock( this ) ) - { - int xp = MathHelper.getRandomIntegerInRange( w.rand, 2, 5 ); - - this.dropXpOnBlockBreak( w, x, y, z, xp ); - } - } - public void setBoostBrightnessLow( int boostBrightnessLow ) { this.boostBrightnessLow = boostBrightnessLow; diff --git a/src/main/java/appeng/block/solids/OreQuartzCharged.java b/src/main/java/appeng/block/solids/OreQuartzCharged.java index 629e27f6a..d074c3d65 100644 --- a/src/main/java/appeng/block/solids/OreQuartzCharged.java +++ b/src/main/java/appeng/block/solids/OreQuartzCharged.java @@ -52,7 +52,7 @@ public class OreQuartzCharged extends OreQuartz @Override public Item getItemDropped( int id, Random rand, int meta ) { - for ( Item charged : AEApi.instance().definitions().materials().certusQuartzCrystalCharged().maybeItem().asSet() ) + for( Item charged : AEApi.instance().definitions().materials().certusQuartzCrystalCharged().maybeItem().asSet() ) { return charged; } @@ -82,7 +82,7 @@ public class OreQuartzCharged extends OreQuartz double yOff = ( r.nextFloat() ); double zOff = ( r.nextFloat() ); - switch ( r.nextInt( 6 ) ) + switch( r.nextInt( 6 ) ) { case 0: xOff = -0.01; @@ -107,11 +107,10 @@ public class OreQuartzCharged extends OreQuartz break; } - if ( CommonHelper.proxy.shouldAddParticles( r ) ) + if( CommonHelper.proxy.shouldAddParticles( r ) ) { ChargedOreFX fx = new ChargedOreFX( w, x + xOff, y + yOff, z + zOff, 0.0f, 0.0f, 0.0f ); Minecraft.getMinecraft().effectRenderer.addEffect( fx ); } } - } diff --git a/src/main/java/appeng/block/spatial/BlockMatrixFrame.java b/src/main/java/appeng/block/spatial/BlockMatrixFrame.java index 81d233f9c..1729444df 100644 --- a/src/main/java/appeng/block/spatial/BlockMatrixFrame.java +++ b/src/main/java/appeng/block/spatial/BlockMatrixFrame.java @@ -18,6 +18,7 @@ package appeng.block.spatial; + import java.util.Arrays; import java.util.EnumSet; import java.util.List; @@ -42,6 +43,7 @@ import appeng.client.render.blocks.RenderNull; import appeng.core.features.AEFeature; import appeng.helpers.ICustomCollision; + public class BlockMatrixFrame extends AEBaseBlock implements ICustomCollision { @@ -62,47 +64,46 @@ public class BlockMatrixFrame extends AEBaseBlock implements ICustomCollision } @Override - @SideOnly(Side.CLIENT) - public void getCheckedSubBlocks(Item item, CreativeTabs tabs, List itemStacks) + public void registerBlockIcons( IIconRegister iconRegistry ) + { + + } + + @Override + @SideOnly( Side.CLIENT ) + public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) { // do nothing } @Override - public void registerBlockIcons(IIconRegister iconRegistry) - { - - } - - @Override - public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity) - { - return false; - } - - @Override - public void onBlockExploded(World world, int x, int y, int z, Explosion explosion) - { - // Don't explode. - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { return Arrays.asList( new AxisAlignedBB[] {} );// AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) - // } ); + // } ); } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); } @Override - public boolean canPlaceBlockAt(World world, int x, int y, int z) + public boolean canPlaceBlockAt( World world, int x, int y, int z ) { return false; } + @Override + public void onBlockExploded( World world, int x, int y, int z, Explosion explosion ) + { + // Don't explode. + } + + @Override + public boolean canEntityDestroy( IBlockAccess world, int x, int y, int z, Entity entity ) + { + return false; + } } diff --git a/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java b/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java index d3ebcd95c..7a56a545a 100644 --- a/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java +++ b/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java @@ -18,6 +18,7 @@ package appeng.block.spatial; + import java.util.EnumSet; import net.minecraft.block.Block; @@ -32,37 +33,38 @@ import appeng.core.sync.GuiBridge; import appeng.tile.spatial.TileSpatialIOPort; import appeng.util.Platform; + public class BlockSpatialIOPort extends AEBaseBlock { - public BlockSpatialIOPort() { + public BlockSpatialIOPort() + { super( BlockSpatialIOPort.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); this.setTileEntity( TileSpatialIOPort.class ); } @Override - public final void onNeighborBlockChange(World w, int x, int y, int z, Block junk) + public final void onNeighborBlockChange( World w, int x, int y, int z, Block junk ) { TileSpatialIOPort te = this.getTileEntity( w, x, y, z ); - if ( te != null ) + if( te != null ) te.updateRedstoneState(); } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) return false; TileSpatialIOPort tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) + if( tg != null ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_SPATIAL_IO_PORT ); return true; } return false; } - } diff --git a/src/main/java/appeng/block/spatial/BlockSpatialPylon.java b/src/main/java/appeng/block/spatial/BlockSpatialPylon.java index 28876e408..b7604d17a 100644 --- a/src/main/java/appeng/block/spatial/BlockSpatialPylon.java +++ b/src/main/java/appeng/block/spatial/BlockSpatialPylon.java @@ -18,6 +18,7 @@ package appeng.block.spatial; + import java.util.EnumSet; import net.minecraft.block.Block; @@ -31,28 +32,30 @@ import appeng.core.features.AEFeature; import appeng.helpers.AEGlassMaterial; import appeng.tile.spatial.TileSpatialPylon; + public class BlockSpatialPylon extends AEBaseBlock { - public BlockSpatialPylon() { + public BlockSpatialPylon() + { super( BlockSpatialPylon.class, AEGlassMaterial.INSTANCE ); this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); this.setTileEntity( TileSpatialPylon.class ); } @Override - public void onNeighborBlockChange(World w, int x, int y, int z, Block junk) + public void onNeighborBlockChange( World w, int x, int y, int z, Block junk ) { TileSpatialPylon tsp = this.getTileEntity( w, x, y, z ); - if ( tsp != null ) + if( tsp != null ) tsp.onNeighborBlockChange(); } @Override - public int getLightValue(IBlockAccess w, int x, int y, int z) + public int getLightValue( IBlockAccess w, int x, int y, int z ) { TileSpatialPylon tsp = this.getTileEntity( w, x, y, z ); - if ( tsp != null ) + if( tsp != null ) return tsp.getLightValue(); return super.getLightValue( w, x, y, z ); } @@ -62,5 +65,4 @@ public class BlockSpatialPylon extends AEBaseBlock { return RenderSpatialPylon.class; } - } diff --git a/src/main/java/appeng/block/storage/BlockChest.java b/src/main/java/appeng/block/storage/BlockChest.java index 448f8f7f6..07a23756b 100644 --- a/src/main/java/appeng/block/storage/BlockChest.java +++ b/src/main/java/appeng/block/storage/BlockChest.java @@ -18,6 +18,7 @@ package appeng.block.storage; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -37,10 +38,12 @@ import appeng.core.sync.GuiBridge; import appeng.tile.storage.TileChest; import appeng.util.Platform; + public class BlockChest extends AEBaseBlock { - public BlockChest() { + public BlockChest() + { super( BlockChest.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.MEChest ) ); this.setTileEntity( TileChest.class ); @@ -53,22 +56,22 @@ public class BlockChest extends AEBaseBlock } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { TileChest tg = this.getTileEntity( w, x, y, z ); - if ( tg != null && !p.isSneaking() ) + if( tg != null && !p.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; - if ( side != tg.getUp().ordinal() ) + if( side != tg.getUp().ordinal() ) { Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CHEST ); } else { ItemStack cell = tg.getStackInSlot( 1 ); - if ( cell != null ) + if( cell != null ) { ICellHandler ch = AEApi.instance().registries().cell().getHandler( cell ); diff --git a/src/main/java/appeng/block/storage/BlockDrive.java b/src/main/java/appeng/block/storage/BlockDrive.java index 4ce958da7..ea5a6dc7e 100644 --- a/src/main/java/appeng/block/storage/BlockDrive.java +++ b/src/main/java/appeng/block/storage/BlockDrive.java @@ -18,6 +18,7 @@ package appeng.block.storage; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -33,10 +34,12 @@ import appeng.core.sync.GuiBridge; import appeng.tile.storage.TileDrive; import appeng.util.Platform; + public class BlockDrive extends AEBaseBlock { - public BlockDrive() { + public BlockDrive() + { super( BlockDrive.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.MEDrive ) ); this.setTileEntity( TileDrive.class ); @@ -49,19 +52,18 @@ public class BlockDrive extends AEBaseBlock } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) return false; TileDrive tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) + if( tg != null ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_DRIVE ); return true; } return false; } - } diff --git a/src/main/java/appeng/block/storage/BlockIOPort.java b/src/main/java/appeng/block/storage/BlockIOPort.java index bf4ea66fa..66958844a 100644 --- a/src/main/java/appeng/block/storage/BlockIOPort.java +++ b/src/main/java/appeng/block/storage/BlockIOPort.java @@ -18,6 +18,7 @@ package appeng.block.storage; + import java.util.EnumSet; import net.minecraft.block.Block; @@ -32,33 +33,35 @@ import appeng.core.sync.GuiBridge; import appeng.tile.storage.TileIOPort; import appeng.util.Platform; + public class BlockIOPort extends AEBaseBlock { - public BlockIOPort() { + public BlockIOPort() + { super( BlockIOPort.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.IOPort ) ); this.setTileEntity( TileIOPort.class ); } @Override - public final void onNeighborBlockChange(World w, int x, int y, int z, Block junk) + public final void onNeighborBlockChange( World w, int x, int y, int z, Block junk ) { TileIOPort te = this.getTileEntity( w, x, y, z ); - if ( te != null ) + if( te != null ) te.updateRedstoneState(); } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) return false; TileIOPort tg = this.getTileEntity( w, x, y, z ); - if ( tg != null ) + if( tg != null ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_IOPORT ); return true; } diff --git a/src/main/java/appeng/block/storage/BlockSkyChest.java b/src/main/java/appeng/block/storage/BlockSkyChest.java index cc7e6c40d..f7328e62c 100644 --- a/src/main/java/appeng/block/storage/BlockSkyChest.java +++ b/src/main/java/appeng/block/storage/BlockSkyChest.java @@ -51,10 +51,12 @@ import appeng.helpers.ICustomCollision; import appeng.tile.storage.TileSkyChest; import appeng.util.Platform; + public class BlockSkyChest extends AEBaseBlock implements ICustomCollision { - public BlockSkyChest() { + public BlockSkyChest() + { super( BlockSkyChest.class, Material.rock ); this.setFeature( EnumSet.of( AEFeature.Core, AEFeature.SkyStoneChests ) ); this.setTileEntity( TileSkyChest.class ); @@ -66,31 +68,11 @@ public class BlockSkyChest extends AEBaseBlock implements ICustomCollision } @Override - public String getUnlocalizedName(ItemStack is) + public int damageDropped( int metadata ) { - if ( is.getItemDamage() == 1 ) - return this.getUnlocalizedName() + ".Block"; - - return this.getUnlocalizedName(); - } - - @Override - public int damageDropped(int metadata) { return metadata; } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int direction, int metadata) - { - for ( Block skyStoneBlock : AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet() ) - { - return skyStoneBlock.getIcon( direction, metadata ); - } - - return Blocks.stone.getIcon( direction, metadata ); - } - @Override public ItemStack getPickBlock( MovingObjectPosition target, World world, int x, int y, int z, EntityPlayer player ) { @@ -101,8 +83,40 @@ public class BlockSkyChest extends AEBaseBlock implements ICustomCollision } @Override - @SideOnly(Side.CLIENT) - public void getCheckedSubBlocks(Item item, CreativeTabs tabs, List itemStacks) + protected Class getRenderer() + { + return RenderBlockSkyChest.class; + } + + @Override + @SideOnly( Side.CLIENT ) + public IIcon getIcon( int direction, int metadata ) + { + for( Block skyStoneBlock : AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet() ) + { + return skyStoneBlock.getIcon( direction, metadata ); + } + + return Blocks.stone.getIcon( direction, metadata ); + } + + @Override + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) + { + if( Platform.isServer() ) + Platform.openGUI( player, this.getTileEntity( w, x, y, z ), ForgeDirection.getOrientation( side ), GuiBridge.GUI_SKYCHEST ); + + return true; + } + + @Override + public void registerBlockIcons( IIconRegister iconRegistry ) + { + } + + @Override + @SideOnly( Side.CLIENT ) + public void getCheckedSubBlocks( Item item, CreativeTabs tabs, List itemStacks ) { super.getCheckedSubBlocks( item, tabs, itemStacks ); @@ -110,28 +124,22 @@ public class BlockSkyChest extends AEBaseBlock implements ICustomCollision } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) + public String getUnlocalizedName( ItemStack is ) { - if ( Platform.isServer() ) - Platform.openGUI( player, this.getTileEntity( w, x, y, z ), ForgeDirection.getOrientation( side ), GuiBridge.GUI_SKYCHEST ); + if( is.getItemDamage() == 1 ) + return this.getUnlocalizedName() + ".Block"; - return true; + return this.getUnlocalizedName(); } @Override - protected Class getRenderer() - { - return RenderBlockSkyChest.class; - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { TileSkyChest sk = this.getTileEntity( w, x, y, z ); double sc = 0.06; ForgeDirection o = ForgeDirection.UNKNOWN; - if ( sk != null ) + if( sk != null ) o = sk.getUp(); double X = o.offsetX == 0 ? 0.06 : 0.0; @@ -142,13 +150,8 @@ public class BlockSkyChest extends AEBaseBlock implements ICustomCollision } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { out.add( AxisAlignedBB.getBoundingBox( 0.05, 0.05, 0.05, 0.95, 0.95, 0.95 ) ); } - - @Override - public void registerBlockIcons(IIconRegister iconRegistry) - { - } } diff --git a/src/main/java/appeng/client/ClientHelper.java b/src/main/java/appeng/client/ClientHelper.java index 5e74d126d..87cdf81f6 100644 --- a/src/main/java/appeng/client/ClientHelper.java +++ b/src/main/java/appeng/client/ClientHelper.java @@ -18,6 +18,7 @@ package appeng.client; + import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -86,64 +87,178 @@ import appeng.util.Platform; import static net.minecraftforge.client.IItemRenderer.ItemRenderType.ENTITY; import static net.minecraftforge.client.IItemRenderer.ItemRendererHelper.BLOCK_3D; + public class ClientHelper extends ServerHelper { private static final RenderItem ITEM_RENDERER = new RenderItem(); private static final RenderBlocks BLOCK_RENDERER = new RenderBlocks(); - @Override - public CableRenderMode getRenderMode() - { - if ( Platform.isServer() ) - return super.getRenderMode(); - - Minecraft mc = Minecraft.getMinecraft(); - EntityPlayer player = mc.thePlayer; - - return this.renderModeForPlayer( player ); - } - - @Override - public void triggerUpdates() - { - Minecraft mc = Minecraft.getMinecraft(); - if ( mc == null || mc.thePlayer == null || mc.theWorld == null ) - return; - - EntityPlayer player = mc.thePlayer; - - if ( player == null ) - return; - - int x = (int) player.posX; - int y = (int) player.posY; - int z = (int) player.posZ; - - int range = 16 * 16; - - mc.theWorld.markBlockRangeForRenderUpdate( x - range, y - range, z - range, x + range, y + range, z + range ); - } - @SubscribeEvent - public void postPlayerRender(RenderLivingEvent.Pre p) + public void postPlayerRender( RenderLivingEvent.Pre p ) { PlayerColor player = TickHandler.INSTANCE.getPlayerColors().get( p.entity.getEntityId() ); - if ( player != null ) + if( player != null ) { AEColor col = player.myColor; - float r = 0xff & (col.mediumVariant >> 16); - float g = 0xff & (col.mediumVariant >> 8); - float b = 0xff & (col.mediumVariant); + float r = 0xff & ( col.mediumVariant >> 16 ); + float g = 0xff & ( col.mediumVariant >> 8 ); + float b = 0xff & ( col.mediumVariant ); GL11.glColor3f( r / 255.0f, g / 255.0f, b / 255.0f ); } } @Override - public void doRenderItem(ItemStack itemstack, World w) + public void init() { - if ( itemstack != null ) + MinecraftForge.EVENT_BUS.register( this ); + } + + @Override + public World getWorld() + { + if( Platform.isClient() ) + return Minecraft.getMinecraft().theWorld; + else + return super.getWorld(); + } + + @Override + public void bindTileEntitySpecialRenderer( Class tile, AEBaseBlock blk ) + { + BaseBlockRender bbr = blk.getRendererInstance().rendererInstance; + if( bbr.hasTESR() && tile != null ) + ClientRegistry.bindTileEntitySpecialRenderer( tile, new TESRWrapper( bbr ) ); + } + + @Override + public List getPlayers() + { + if( Platform.isClient() ) + { + List o = new ArrayList(); + o.add( Minecraft.getMinecraft().thePlayer ); + return o; + } + else + return super.getPlayers(); + } + + @Override + public void spawnEffect( EffectType effect, World worldObj, double posX, double posY, double posZ, Object o ) + { + if( AEConfig.instance.enableEffects ) + { + switch( effect ) + { + case Assembler: + this.spawnAssembler( worldObj, posX, posY, posZ, o ); + return; + case Vibrant: + this.spawnVibrant( worldObj, posX, posY, posZ ); + return; + case Crafting: + this.spawnCrafting( worldObj, posX, posY, posZ ); + return; + case Energy: + this.spawnEnergy( worldObj, posX, posY, posZ ); + return; + case Lightning: + this.spawnLightning( worldObj, posX, posY, posZ ); + return; + case LightningArc: + this.spawnLightningArc( worldObj, posX, posY, posZ, (Vec3) o ); + return; + default: + } + } + } + + private void spawnAssembler( World worldObj, double posX, double posY, double posZ, Object o ) + { + PacketAssemblerAnimation paa = (PacketAssemblerAnimation) o; + + AssemblerFX fx = new AssemblerFX( Minecraft.getMinecraft().theWorld, posX, posY, posZ, 0.0D, 0.0D, 0.0D, paa.rate, paa.is ); + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + + private void spawnVibrant( World w, double x, double y, double z ) + { + if( CommonHelper.proxy.shouldAddParticles( Platform.getRandom() ) ) + { + double d0 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; + double d1 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; + double d2 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; + + VibrantFX fx = new VibrantFX( w, x + d0, y + d1, z + d2, 0.0D, 0.0D, 0.0D ); + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + } + + private void spawnCrafting( World w, double posX, double posY, double posZ ) + { + float x = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + float y = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + float z = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + + CraftingFx fx = new CraftingFx( w, posX + x, posY + y, posZ + z, Items.diamond ); + + fx.motionX = -x * 0.2; + fx.motionY = -y * 0.2; + fx.motionZ = -z * 0.2; + + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + + private void spawnEnergy( World w, double posX, double posY, double posZ ) + { + float x = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + float y = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + float z = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + + EnergyFx fx = new EnergyFx( w, posX + x, posY + y, posZ + z, Items.diamond ); + + fx.motionX = -x * 0.1; + fx.motionY = -y * 0.1; + fx.motionZ = -z * 0.1; + + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + + private void spawnLightning( World worldObj, double posX, double posY, double posZ ) + { + LightningFX fx = new LightningFX( worldObj, posX, posY + 0.3f, posZ, 0.0f, 0.0f, 0.0f ); + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + + private void spawnLightningArc( World worldObj, double posX, double posY, double posZ, Vec3 second ) + { + LightningFX fx = new LightningArcFX( worldObj, posX, posY, posZ, second.xCoord, second.yCoord, second.zCoord, 0.0f, 0.0f, 0.0f ); + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + + @Override + public boolean shouldAddParticles( Random r ) + { + int setting = Minecraft.getMinecraft().gameSettings.particleSetting; + if( setting == 2 ) + return false; + if( setting == 0 ) + return true; + return r.nextInt( 2 * ( setting + 1 ) ) == 0; + } + + @Override + public MovingObjectPosition getMOP() + { + return Minecraft.getMinecraft().objectMouseOver; + } + + @Override + public void doRenderItem( ItemStack itemstack, World w ) + { + if( itemstack != null ) { EntityItem entityitem = new EntityItem( w, 0.0D, 0.0D, 0.0D, itemstack ); entityitem.getEntityItem().stackSize = 1; @@ -158,7 +273,7 @@ public class ClientHelper extends ServerHelper GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); // GL11.glDisable( GL11.GL_CULL_FACE ); - if ( itemstack.isItemEnchanted() || itemstack.getItem().requiresMultipleRenderPasses() ) + if( itemstack.isItemEnchanted() || itemstack.getItem().requiresMultipleRenderPasses() ) { GL11.glTranslatef( 0.0f, -0.05f, -0.25f ); GL11.glScalef( 1.0f / 1.5f, 1.0f / 1.5f, 1.0f / 1.5f ); @@ -167,7 +282,7 @@ public class ClientHelper extends ServerHelper // GL11.glScalef( 1.0f , -1.0f, 1.0f ); Block block = Block.getBlockFromItem( itemstack.getItem() ); - if ( (itemstack.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( block.getRenderType() )) ) + if( ( itemstack.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( block.getRenderType() ) ) ) { GL11.glRotatef( 25.0f, 1.0f, 0.0f, 0.0f ); GL11.glRotatef( 15.0f, 0.0f, 1.0f, 0.0f ); @@ -175,9 +290,9 @@ public class ClientHelper extends ServerHelper } IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer( itemstack, ENTITY ); - if ( customRenderer != null && !(itemstack.getItem() instanceof ItemBlock) ) + if( customRenderer != null && !( itemstack.getItem() instanceof ItemBlock ) ) { - if ( customRenderer.shouldUseRenderHelper( ENTITY, itemstack, BLOCK_3D ) ) + if( customRenderer.shouldUseRenderHelper( ENTITY, itemstack, BLOCK_3D ) ) { GL11.glTranslatef( 0, -0.04F, 0 ); GL11.glScalef( 0.7f, 0.7f, 0.7f ); @@ -186,7 +301,7 @@ public class ClientHelper extends ServerHelper GL11.glRotatef( -90, 0, 1, 0 ); } } - else if ( itemstack.getItem() instanceof ItemBlock ) + else if( itemstack.getItem() instanceof ItemBlock ) { GL11.glTranslatef( 0, -0.04F, 0 ); GL11.glScalef( 1.1f, 1.1f, 1.1f ); @@ -210,7 +325,7 @@ public class ClientHelper extends ServerHelper RenderItem.renderInFrame = false; FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - if ( !ForgeHooksClient.renderInventoryItem( BLOCK_RENDERER, Minecraft.getMinecraft().renderEngine, itemstack, true, 0, 0, 0 ) ) + if( !ForgeHooksClient.renderInventoryItem( BLOCK_RENDERER, Minecraft.getMinecraft().renderEngine, itemstack, true, 0, 0, 0 ) ) { ITEM_RENDERER.renderItemIntoGUI( fr, Minecraft.getMinecraft().renderEngine, itemstack, 0, 0, false ); } @@ -220,12 +335,6 @@ public class ClientHelper extends ServerHelper } } - @Override - public void init() - { - MinecraftForge.EVENT_BUS.register( this ); - } - @Override public void postInit() { @@ -234,187 +343,37 @@ public class ClientHelper extends ServerHelper RenderManager.instance.entityRenderMap.put( EntityFloatingItem.class, new RenderFloatingItem() ); } - @SubscribeEvent - public void wheelEvent(MouseEvent me) + @Override + public CableRenderMode getRenderMode() { - if ( me.isCanceled() || me.dwheel == 0 ) - return; + if( Platform.isServer() ) + return super.getRenderMode(); Minecraft mc = Minecraft.getMinecraft(); EntityPlayer player = mc.thePlayer; - ItemStack is = player.getHeldItem(); - if ( is != null && is.getItem() instanceof IMouseWheelItem && player.isSneaking() ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "Item", me.dwheel > 0 ? "WheelUp" : "WheelDown" ) ); - me.setCanceled( true ); - } - catch (IOException e) - { - AELog.error( e ); - } - } - } - - @SubscribeEvent - public void updateTextureSheet(TextureStitchEvent.Pre ev) - { - if ( ev.map.getTextureType() == 1 ) - { - for (ExtraItemTextures et : ExtraItemTextures.values()) - et.registerIcon( ev.map ); - } - - if ( ev.map.getTextureType() == 0 ) - { - for (ExtraBlockTextures et : ExtraBlockTextures.values()) - et.registerIcon( ev.map ); - - for (CableBusTextures cb : CableBusTextures.values()) - cb.registerIcon( ev.map ); - } + return this.renderModeForPlayer( player ); } @Override - public World getWorld() + public void triggerUpdates() { - if ( Platform.isClient() ) - return Minecraft.getMinecraft().theWorld; - else - return super.getWorld(); - } + Minecraft mc = Minecraft.getMinecraft(); + if( mc == null || mc.thePlayer == null || mc.theWorld == null ) + return; - @Override - public void bindTileEntitySpecialRenderer(Class tile, AEBaseBlock blk) - { - BaseBlockRender bbr = blk.getRendererInstance().rendererInstance; - if ( bbr.hasTESR() && tile != null ) - ClientRegistry.bindTileEntitySpecialRenderer( tile, new TESRWrapper( bbr ) ); - } + EntityPlayer player = mc.thePlayer; - @Override - public List getPlayers() - { - if ( Platform.isClient() ) - { - List o = new ArrayList(); - o.add( Minecraft.getMinecraft().thePlayer ); - return o; - } - else - return super.getPlayers(); - } + if( player == null ) + return; - @Override - public void spawnEffect(EffectType effect, World worldObj, double posX, double posY, double posZ, Object o) - { - if ( AEConfig.instance.enableEffects ) - { - switch (effect) - { - case Assembler: - this.spawnAssembler( worldObj, posX, posY, posZ, o ); - return; - case Vibrant: - this.spawnVibrant( worldObj, posX, posY, posZ ); - return; - case Crafting: - this.spawnCrafting( worldObj, posX, posY, posZ ); - return; - case Energy: - this.spawnEnergy( worldObj, posX, posY, posZ ); - return; - case Lightning: - this.spawnLightning( worldObj, posX, posY, posZ ); - return; - case LightningArc: - this.spawnLightningArc( worldObj, posX, posY, posZ, (Vec3) o ); - return; - default: - } - } - } + int x = (int) player.posX; + int y = (int) player.posY; + int z = (int) player.posZ; - private void spawnAssembler(World worldObj, double posX, double posY, double posZ, Object o) - { - PacketAssemblerAnimation paa = (PacketAssemblerAnimation) o; + int range = 16 * 16; - AssemblerFX fx = new AssemblerFX( Minecraft.getMinecraft().theWorld, posX, posY, posZ, 0.0D, 0.0D, 0.0D, paa.rate, paa.is ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - private void spawnVibrant(World w, double x, double y, double z) - { - if ( CommonHelper.proxy.shouldAddParticles( Platform.getRandom() ) ) - { - double d0 = (Platform.getRandomFloat() - 0.5F) * 0.26D; - double d1 = (Platform.getRandomFloat() - 0.5F) * 0.26D; - double d2 = (Platform.getRandomFloat() - 0.5F) * 0.26D; - - VibrantFX fx = new VibrantFX( w, x + d0, y + d1, z + d2, 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - - private void spawnLightningArc(World worldObj, double posX, double posY, double posZ, Vec3 second) - { - LightningFX fx = new LightningArcFX( worldObj, posX, posY, posZ, second.xCoord, second.yCoord, second.zCoord, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - private void spawnLightning(World worldObj, double posX, double posY, double posZ) - { - LightningFX fx = new LightningFX( worldObj, posX, posY + 0.3f, posZ, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - private void spawnEnergy(World w, double posX, double posY, double posZ) - { - float x = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - float y = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - float z = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - - EnergyFx fx = new EnergyFx( w, posX + x, posY + y, posZ + z, Items.diamond ); - - fx.motionX = -x * 0.1; - fx.motionY = -y * 0.1; - fx.motionZ = -z * 0.1; - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - private void spawnCrafting(World w, double posX, double posY, double posZ) - { - float x = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - float y = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - float z = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - - CraftingFx fx = new CraftingFx( w, posX + x, posY + y, posZ + z, Items.diamond ); - - fx.motionX = -x * 0.2; - fx.motionY = -y * 0.2; - fx.motionZ = -z * 0.2; - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - @Override - public boolean shouldAddParticles(Random r) - { - int setting = Minecraft.getMinecraft().gameSettings.particleSetting; - if ( setting == 2 ) - return false; - if ( setting == 0 ) - return true; - return r.nextInt( 2 * (setting + 1) ) == 0; - } - - @Override - public MovingObjectPosition getMOP() - { - return Minecraft.getMinecraft().objectMouseOver; + mc.theWorld.markBlockRangeForRenderUpdate( x - range, y - range, z - range, x + range, y + range, z + range ); } @Override @@ -423,4 +382,46 @@ public class ClientHelper extends ServerHelper throw new MissingCoreMod(); } + @SubscribeEvent + public void wheelEvent( MouseEvent me ) + { + if( me.isCanceled() || me.dwheel == 0 ) + return; + + Minecraft mc = Minecraft.getMinecraft(); + EntityPlayer player = mc.thePlayer; + ItemStack is = player.getHeldItem(); + + if( is != null && is.getItem() instanceof IMouseWheelItem && player.isSneaking() ) + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "Item", me.dwheel > 0 ? "WheelUp" : "WheelDown" ) ); + me.setCanceled( true ); + } + catch( IOException e ) + { + AELog.error( e ); + } + } + } + + @SubscribeEvent + public void updateTextureSheet( TextureStitchEvent.Pre ev ) + { + if( ev.map.getTextureType() == 1 ) + { + for( ExtraItemTextures et : ExtraItemTextures.values() ) + et.registerIcon( ev.map ); + } + + if( ev.map.getTextureType() == 0 ) + { + for( ExtraBlockTextures et : ExtraBlockTextures.values() ) + et.registerIcon( ev.map ); + + for( CableBusTextures cb : CableBusTextures.values() ) + cb.registerIcon( ev.map ); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/client/EffectType.java b/src/main/java/appeng/client/EffectType.java index 57bd32a38..8929909e5 100644 --- a/src/main/java/appeng/client/EffectType.java +++ b/src/main/java/appeng/client/EffectType.java @@ -18,6 +18,7 @@ package appeng.client; + public enum EffectType { Energy, Lightning, Vibrant, Crafting, Assembler, LightningArc diff --git a/src/main/java/appeng/client/gui/AEBaseGui.java b/src/main/java/appeng/client/gui/AEBaseGui.java index 4c57ebdb6..9836e7112 100644 --- a/src/main/java/appeng/client/gui/AEBaseGui.java +++ b/src/main/java/appeng/client/gui/AEBaseGui.java @@ -613,6 +613,21 @@ public abstract class AEBaseGui extends GuiContainer this.subGui = true; // in case the gui is reopened later ( i'm looking at you NEI ) } + protected Slot getSlot( int mouseX, int mouseY ) + { + final List slots = this.getInventorySlots(); + for( Slot slot : slots ) + { + // isPointInRegion + if( this.func_146978_c( slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX, mouseY ) ) + { + return slot; + } + } + + return null; + } + public abstract void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ); @Override @@ -652,21 +667,6 @@ public abstract class AEBaseGui extends GuiContainer } } - protected Slot getSlot( int mouseX, int mouseY ) - { - final List slots = this.getInventorySlots(); - for( Slot slot : slots ) - { - // isPointInRegion - if( this.func_146978_c( slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX, mouseY ) ) - { - return slot; - } - } - - return null; - } - protected boolean enableSpaceClicking() { return true; diff --git a/src/main/java/appeng/client/gui/AEBaseMEGui.java b/src/main/java/appeng/client/gui/AEBaseMEGui.java index 9034ba16d..c19d271bd 100644 --- a/src/main/java/appeng/client/gui/AEBaseMEGui.java +++ b/src/main/java/appeng/client/gui/AEBaseMEGui.java @@ -18,6 +18,7 @@ package appeng.client.gui; + import java.text.NumberFormat; import java.util.List; import java.util.Locale; @@ -30,19 +31,21 @@ import appeng.api.storage.data.IAEItemStack; import appeng.client.me.SlotME; import appeng.core.AEConfig; + public abstract class AEBaseMEGui extends AEBaseGui { - public AEBaseMEGui(Container container) { + public AEBaseMEGui( Container container ) + { super( container ); } - public List handleItemTooltip(ItemStack stack, int mouseX, int mouseY, List currentToolTip) + public List handleItemTooltip( ItemStack stack, int mouseX, int mouseY, List currentToolTip ) { - if ( stack != null ) + if( stack != null ) { Slot s = this.getSlot( mouseX, mouseY ); - if ( s instanceof SlotME ) + if( s instanceof SlotME ) { int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; @@ -53,19 +56,19 @@ public abstract class AEBaseMEGui extends AEBaseGui SlotME theSlotField = (SlotME) s; myStack = theSlotField.getAEStack(); } - catch (Throwable ignore) + catch( Throwable ignore ) { } - if ( myStack != null ) + if( myStack != null ) { - if ( myStack.getStackSize() > BigNumber || (myStack.getStackSize() > 1 && stack.isItemDamaged()) ) + if( myStack.getStackSize() > BigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) currentToolTip.add( "\u00a77Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ) ); - if ( myStack.getCountRequestable() > 0 ) + if( myStack.getCountRequestable() > 0 ) currentToolTip.add( "\u00a77Items Requestable: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getCountRequestable() ) ); } - else if ( stack.stackSize > BigNumber || (stack.stackSize > 1 && stack.isItemDamaged()) ) + else if( stack.stackSize > BigNumber || ( stack.stackSize > 1 && stack.isItemDamaged() ) ) { currentToolTip.add( "\u00a77Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( stack.stackSize ) ); } @@ -77,10 +80,10 @@ public abstract class AEBaseMEGui extends AEBaseGui // Vanilla version... // protected void drawItemStackTooltip(ItemStack stack, int x, int y) @Override - protected void renderToolTip(ItemStack stack, int x, int y) + protected void renderToolTip( ItemStack stack, int x, int y ) { Slot s = this.getSlot( x, y ); - if ( s instanceof SlotME && stack != null ) + if( s instanceof SlotME && stack != null ) { int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; @@ -91,24 +94,24 @@ public abstract class AEBaseMEGui extends AEBaseGui SlotME theSlotField = (SlotME) s; myStack = theSlotField.getAEStack(); } - catch (Throwable ignore) + catch( Throwable ignore ) { } - if ( myStack != null ) + if( myStack != null ) { @SuppressWarnings( "unchecked" ) List currentToolTip = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); - if ( myStack.getStackSize() > BigNumber || (myStack.getStackSize() > 1 && stack.isItemDamaged()) ) + if( myStack.getStackSize() > BigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) currentToolTip.add( "Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ) ); - if ( myStack.getCountRequestable() > 0 ) + if( myStack.getCountRequestable() > 0 ) currentToolTip.add( "Items Requestable: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getCountRequestable() ) ); this.drawTooltip( x, y, 0, join( currentToolTip, "\n" ) ); } - else if ( stack.stackSize > BigNumber ) + else if( stack.stackSize > BigNumber ) { List var4 = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); var4.add( "Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( stack.stackSize ) ); @@ -119,5 +122,4 @@ public abstract class AEBaseMEGui extends AEBaseGui super.renderToolTip( stack, x, y ); // super.drawItemStackTooltip( stack, x, y ); } - } \ No newline at end of file diff --git a/src/main/java/appeng/client/gui/GuiNull.java b/src/main/java/appeng/client/gui/GuiNull.java index 5b1e23343..743b3c334 100644 --- a/src/main/java/appeng/client/gui/GuiNull.java +++ b/src/main/java/appeng/client/gui/GuiNull.java @@ -18,24 +18,26 @@ package appeng.client.gui; + import net.minecraft.inventory.Container; + public class GuiNull extends AEBaseGui { - public GuiNull(Container container) { + public GuiNull( Container container ) + { super( container ); } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - } @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) { - } + } } diff --git a/src/main/java/appeng/client/gui/config/AEConfigGui.java b/src/main/java/appeng/client/gui/config/AEConfigGui.java index 3e33cf109..ff19afb97 100644 --- a/src/main/java/appeng/client/gui/config/AEConfigGui.java +++ b/src/main/java/appeng/client/gui/config/AEConfigGui.java @@ -32,24 +32,30 @@ import cpw.mods.fml.client.config.IConfigElement; import appeng.core.AEConfig; import appeng.core.AppEng; + public class AEConfigGui extends GuiConfig { + public AEConfigGui( GuiScreen parent ) + { + super( parent, getConfigElements(), AppEng.MOD_ID, false, false, GuiConfig.getAbridgedConfigPath( AEConfig.instance.getFilePath() ) ); + } + private static List getConfigElements() { List list = new ArrayList(); - for (String cat : AEConfig.instance.getCategoryNames()) + for( String cat : AEConfig.instance.getCategoryNames() ) { - if ( cat.equals( "versionchecker" ) ) + if( cat.equals( "versionchecker" ) ) continue; - if ( cat.equals( "settings" ) ) + if( cat.equals( "settings" ) ) continue; ConfigCategory cc = AEConfig.instance.getCategory( cat ); - if ( cc.isChild() ) + if( cc.isChild() ) continue; ConfigElement ce = new ConfigElement( cc ); @@ -58,9 +64,4 @@ public class AEConfigGui extends GuiConfig return list; } - - public AEConfigGui(GuiScreen parent) { - super( parent, getConfigElements(), AppEng.MOD_ID, false, false, GuiConfig.getAbridgedConfigPath( AEConfig.instance.getFilePath() ) ); - } - } diff --git a/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java b/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java index 4baea37bb..a1c669303 100644 --- a/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java +++ b/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java @@ -18,6 +18,7 @@ package appeng.client.gui.config; + import java.util.Set; import net.minecraft.client.Minecraft; @@ -25,11 +26,12 @@ import net.minecraft.client.gui.GuiScreen; import cpw.mods.fml.client.IModGuiFactory; + public class AEConfigGuiFactory implements IModGuiFactory { @Override - public void initialize(Minecraft minecraftInstance) + public void initialize( Minecraft minecraftInstance ) { } @@ -47,9 +49,8 @@ public class AEConfigGuiFactory implements IModGuiFactory } @Override - public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) + public RuntimeOptionGuiHandler getHandlerFor( RuntimeOptionCategoryElement element ) { return null; } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java b/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java index e0390247d..8ef12c64d 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import java.io.IOException; import org.lwjgl.input.Mouse; @@ -42,6 +43,7 @@ import appeng.core.sync.packets.PacketValueConfig; import appeng.tile.misc.TileCellWorkbench; import appeng.util.Platform; + public class GuiCellWorkbench extends GuiUpgradeable { @@ -52,100 +54,14 @@ public class GuiCellWorkbench extends GuiUpgradeable GuiImgButton partition; GuiToggleButton copyMode; - public GuiCellWorkbench(InventoryPlayer inventoryPlayer, TileCellWorkbench te) { + public GuiCellWorkbench( InventoryPlayer inventoryPlayer, TileCellWorkbench te ) + { super( new ContainerCellWorkbench( inventoryPlayer, te ) ); this.workbench = (ContainerCellWorkbench) this.inventorySlots; this.ySize = 251; this.tcw = te; } - @Override - protected boolean drawUpgrades() - { - return this.workbench.availableUpgrades() > 0; - } - - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.handleButtonVisibility(); - - this.bindTexture( this.getBackground() ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - if ( this.drawUpgrades() ) - { - if ( this.workbench.availableUpgrades() <= 8 ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + this.workbench.availableUpgrades() * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + (7 + (this.workbench.availableUpgrades()) * 18), 177, 151, 35, 7 ); - } - else if ( this.workbench.availableUpgrades() <= 16 ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + (7 + (8) * 18), 177, 151, 35, 7 ); - - int dx = this.workbench.availableUpgrades() - 8; - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + dx * 18 ); - if ( dx == 8 ) - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY + (7 + (dx) * 18), 186, 151, 35 - 8, 7 ); - else - this.drawTexturedModalRect( offsetX + 177 + 27 + 4, offsetY + (7 + (dx) * 18), 186 + 4, 151, 35 - 8, 7 ); - - } - else - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + (7 + (8) * 18), 177, 151, 35, 7 ); - - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY + (7 + (8) * 18), 186, 151, 35 - 8, 7 ); - - int dx = this.workbench.availableUpgrades() - 16; - this.drawTexturedModalRect( offsetX + 177 + 27 + 18, offsetY, 186, 0, 35 - 8, 7 + dx * 18 ); - if ( dx == 8 ) - this.drawTexturedModalRect( offsetX + 177 + 27 + 18, offsetY + (7 + (dx) * 18), 186, 151, 35 - 8, 7 ); - else - this.drawTexturedModalRect( offsetX + 177 + 27 + 18 + 4, offsetY + (7 + (dx) * 18), 186 + 4, 151, 35 - 8, 7 ); - } - } - if ( this.hasToolbox() ) - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, 161, 68, 68 ); - } - - @Override - protected void actionPerformed(GuiButton btn) - { - try - { - if ( btn == this.copyMode ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "CopyMode" ) ); - } - else if ( btn == this.partition ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "Partition" ) ); - } - else if ( btn == this.clear ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "Clear" ) ); - } - else if ( btn == this.fuzzyMode ) - { - boolean backwards = Mouse.isButtonDown( 1 ); - - FuzzyMode fz = (FuzzyMode) this.fuzzyMode.getCurrentValue(); - fz = Platform.rotateEnum( fz, backwards, Settings.FUZZY_MODE.getPossibleValues() ); - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Fuzzy", fz.name() ) ); - } - else - super.actionPerformed( btn ); - } - catch (IOException ignored) - { - } - } - @Override protected void addButtons() { @@ -160,6 +76,52 @@ public class GuiCellWorkbench extends GuiUpgradeable this.buttonList.add( this.copyMode ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.handleButtonVisibility(); + + this.bindTexture( this.getBackground() ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); + if( this.drawUpgrades() ) + { + if( this.workbench.availableUpgrades() <= 8 ) + { + this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + this.workbench.availableUpgrades() * 18 ); + this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( this.workbench.availableUpgrades() ) * 18 ), 177, 151, 35, 7 ); + } + else if( this.workbench.availableUpgrades() <= 16 ) + { + this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18 ); + this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( 8 ) * 18 ), 177, 151, 35, 7 ); + + int dx = this.workbench.availableUpgrades() - 8; + this.drawTexturedModalRect( offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + dx * 18 ); + if( dx == 8 ) + this.drawTexturedModalRect( offsetX + 177 + 27, offsetY + ( 7 + ( dx ) * 18 ), 186, 151, 35 - 8, 7 ); + else + this.drawTexturedModalRect( offsetX + 177 + 27 + 4, offsetY + ( 7 + ( dx ) * 18 ), 186 + 4, 151, 35 - 8, 7 ); + } + else + { + this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18 ); + this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( 8 ) * 18 ), 177, 151, 35, 7 ); + + this.drawTexturedModalRect( offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + 8 * 18 ); + this.drawTexturedModalRect( offsetX + 177 + 27, offsetY + ( 7 + ( 8 ) * 18 ), 186, 151, 35 - 8, 7 ); + + int dx = this.workbench.availableUpgrades() - 16; + this.drawTexturedModalRect( offsetX + 177 + 27 + 18, offsetY, 186, 0, 35 - 8, 7 + dx * 18 ); + if( dx == 8 ) + this.drawTexturedModalRect( offsetX + 177 + 27 + 18, offsetY + ( 7 + ( dx ) * 18 ), 186, 151, 35 - 8, 7 ); + else + this.drawTexturedModalRect( offsetX + 177 + 27 + 18 + 4, offsetY + ( 7 + ( dx ) * 18 ), 186 + 4, 151, 35 - 8, 7 ); + } + } + if( this.hasToolbox() ) + this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, 161, 68, 68 ); + } + @Override protected void handleButtonVisibility() { @@ -167,12 +129,12 @@ public class GuiCellWorkbench extends GuiUpgradeable boolean hasFuzzy = false; IInventory inv = this.workbench.getCellUpgradeInventory(); - for (int x = 0; x < inv.getSizeInventory(); x++) + for( int x = 0; x < inv.getSizeInventory(); x++ ) { ItemStack is = inv.getStackInSlot( x ); - if ( is != null && is.getItem() instanceof IUpgradeModule ) + if( is != null && is.getItem() instanceof IUpgradeModule ) { - if ( ((IUpgradeModule) is.getItem()).getType( is ) == Upgrades.FUZZY ) + if( ( (IUpgradeModule) is.getItem() ).getType( is ) == Upgrades.FUZZY ) hasFuzzy = true; } } @@ -185,9 +147,49 @@ public class GuiCellWorkbench extends GuiUpgradeable return "guis/cellworkbench.png"; } + @Override + protected boolean drawUpgrades() + { + return this.workbench.availableUpgrades() > 0; + } + @Override protected GuiText getName() { return GuiText.CellWorkbench; } + + @Override + protected void actionPerformed( GuiButton btn ) + { + try + { + if( btn == this.copyMode ) + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "CopyMode" ) ); + } + else if( btn == this.partition ) + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "Partition" ) ); + } + else if( btn == this.clear ) + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "Clear" ) ); + } + else if( btn == this.fuzzyMode ) + { + boolean backwards = Mouse.isButtonDown( 1 ); + + FuzzyMode fz = (FuzzyMode) this.fuzzyMode.getCurrentValue(); + fz = Platform.rotateEnum( fz, backwards, Settings.FUZZY_MODE.getPossibleValues() ); + + NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Fuzzy", fz.name() ) ); + } + else + super.actionPerformed( btn ); + } + catch( IOException ignored ) + { + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiChest.java b/src/main/java/appeng/client/gui/implementations/GuiChest.java index f066edcde..75bb50bf4 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiChest.java +++ b/src/main/java/appeng/client/gui/implementations/GuiChest.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; @@ -30,17 +31,24 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.tile.storage.TileChest; + public class GuiChest extends AEBaseGui { GuiTabButton priority; + public GuiChest( InventoryPlayer inventoryPlayer, TileChest te ) + { + super( new ContainerChest( inventoryPlayer, te ) ); + this.ySize = 166; + } + @Override - protected void actionPerformed(GuiButton par1GuiButton) + protected void actionPerformed( GuiButton par1GuiButton ) { super.actionPerformed( par1GuiButton ); - if ( par1GuiButton == this.priority ) + if( par1GuiButton == this.priority ) { NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); } @@ -54,23 +62,17 @@ public class GuiChest extends AEBaseGui this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); } - public GuiChest(InventoryPlayer inventoryPlayer, TileChest te) { - super( new ContainerChest( inventoryPlayer, te ) ); - this.ySize = 166; - } - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/chest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Chest.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/chest.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCondenser.java b/src/main/java/appeng/client/gui/implementations/GuiCondenser.java index 73e099e3e..7b1577011 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCondenser.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCondenser.java @@ -35,6 +35,7 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.tile.misc.TileCondenser; + public class GuiCondenser extends AEBaseGui { @@ -42,7 +43,7 @@ public class GuiCondenser extends AEBaseGui GuiProgressBar pb; GuiImgButton mode; - public GuiCondenser(InventoryPlayer inventoryPlayer, TileCondenser te) + public GuiCondenser( InventoryPlayer inventoryPlayer, TileCondenser te ) { super( new ContainerCondenser( inventoryPlayer, te ) ); this.cvc = (ContainerCondenser) this.inventorySlots; @@ -50,13 +51,13 @@ public class GuiCondenser extends AEBaseGui } @Override - protected void actionPerformed(GuiButton btn) + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); boolean backwards = Mouse.isButtonDown( 1 ); - if ( this.mode == btn ) + if( this.mode == btn ) { NetworkHandler.instance.sendToServer( new PacketConfigButton( Settings.CONDENSER_OUTPUT, backwards ) ); } @@ -76,22 +77,20 @@ public class GuiCondenser extends AEBaseGui } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/condenser.png" ); - - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Condenser.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); this.mode.set( this.cvc.output ); this.mode.fillVar = String.valueOf( this.cvc.output.requiredPower ); - } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/condenser.png" ); + + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java b/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java index 0992914d5..672ecf74a 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; @@ -43,6 +44,7 @@ import appeng.parts.reporting.PartCraftingTerminal; import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartTerminal; + public class GuiCraftAmount extends AEBaseGui { private GuiNumberBox amountToCraft; @@ -62,7 +64,8 @@ public class GuiCraftAmount extends AEBaseGui private GuiBridge originalGui; @Reflected - public GuiCraftAmount(InventoryPlayer inventoryPlayer, ITerminalHost te) { + public GuiCraftAmount( InventoryPlayer inventoryPlayer, ITerminalHost te ) + { super( new ContainerCraftAmount( inventoryPlayer, te ) ); } @@ -89,13 +92,13 @@ public class GuiCraftAmount extends AEBaseGui this.buttonList.add( this.next = new GuiButton( 0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal() ) ); ItemStack myIcon = null; - Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); + Object target = ( (AEBaseContainer) this.inventorySlots ).getTarget(); final IDefinitions definitions = AEApi.instance().definitions(); final IParts parts = definitions.parts(); - if ( target instanceof WirelessTerminalGuiObject ) + if( target instanceof WirelessTerminalGuiObject ) { - for ( ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) + for( ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) { myIcon = wirelessTerminalStack; } @@ -103,34 +106,34 @@ public class GuiCraftAmount extends AEBaseGui this.originalGui = GuiBridge.GUI_WIRELESS_TERM; } - if ( target instanceof PartTerminal ) + if( target instanceof PartTerminal ) { - for ( ItemStack stack : parts.terminal().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.terminal().maybeStack( 1 ).asSet() ) { myIcon = stack; } this.originalGui = GuiBridge.GUI_ME; } - if ( target instanceof PartCraftingTerminal ) + if( target instanceof PartCraftingTerminal ) { - for ( ItemStack stack : parts.craftingTerminal().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.craftingTerminal().maybeStack( 1 ).asSet() ) { myIcon = stack; } this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; } - if ( target instanceof PartPatternTerminal ) + if( target instanceof PartPatternTerminal ) { - for ( ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) { myIcon = stack; } this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; } - if ( this.originalGui != null && myIcon != null ) + if( this.originalGui != null && myIcon != null ) { this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender ) ); } @@ -145,111 +148,67 @@ public class GuiCraftAmount extends AEBaseGui } @Override - protected void actionPerformed(GuiButton btn) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - super.actionPerformed( btn ); - - try - { - - if ( btn == this.originalGuiBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); - } - - if ( btn == this.next ) - { - NetworkHandler.instance.sendToServer( new PacketCraftRequest( Integer.parseInt( this.amountToCraft.getText() ), isShiftKeyDown() ) ); - } - - } - catch (NumberFormatException e) - { - // nope.. - this.amountToCraft.setText( "1" ); - } - - boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - - if ( isPlus || isMinus ) - this.addQty( this.getQty( btn ) ); - } - - private void addQty(int i) - { - try - { - String out = this.amountToCraft.getText(); - - boolean fixed = false; - while (out.startsWith( "0" ) && out.length() > 1) - { - out = out.substring( 1 ); - fixed = true; - } - - if ( fixed ) - this.amountToCraft.setText( out ); - - if ( out.length() == 0 ) - out = "0"; - - long result = Integer.parseInt( out ); - - if ( result == 1 && i > 1 ) - result = 0; - - result += i; - if ( result < 1 ) - result = 1; - - out = Long.toString( result ); - Integer.parseInt( out ); - this.amountToCraft.setText( out ); - } - catch (NumberFormatException e) - { - // :P - } + this.fontRendererObj.drawString( GuiText.SelectAmount.getLocal(), 8, 6, 4210752 ); } @Override - protected void keyTyped(char character, int key) + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) { - if ( !this.checkHotbarKeys( key ) ) + this.next.displayString = isShiftKeyDown() ? GuiText.Start.getLocal() : GuiText.Next.getLocal(); + + this.bindTexture( "guis/craftAmt.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + + try { - if ( key == 28 ) + Long.parseLong( this.amountToCraft.getText() ); + this.next.enabled = this.amountToCraft.getText().length() > 0; + } + catch( NumberFormatException e ) + { + this.next.enabled = false; + } + + this.amountToCraft.drawTextBox(); + } + + @Override + protected void keyTyped( char character, int key ) + { + if( !this.checkHotbarKeys( key ) ) + { + if( key == 28 ) { this.actionPerformed( this.next ); } - if ( (key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit( character )) - && this.amountToCraft.textboxKeyTyped( character, key ) ) + if( ( key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit( character ) ) && this.amountToCraft.textboxKeyTyped( character, key ) ) { try { String out = this.amountToCraft.getText(); boolean fixed = false; - while (out.startsWith( "0" ) && out.length() > 1) + while( out.startsWith( "0" ) && out.length() > 1 ) { out = out.substring( 1 ); fixed = true; } - if ( fixed ) + if( fixed ) this.amountToCraft.setText( out ); - if ( out.length() == 0 ) + if( out.length() == 0 ) out = "0"; long result = Long.parseLong( out ); - if ( result < 0 ) + if( result < 0 ) { this.amountToCraft.setText( "1" ); } } - catch (NumberFormatException e) + catch( NumberFormatException e ) { // :P } @@ -262,34 +221,76 @@ public class GuiCraftAmount extends AEBaseGui } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) + protected void actionPerformed( GuiButton btn ) { - this.next.displayString = isShiftKeyDown() ? GuiText.Start.getLocal() : GuiText.Next.getLocal(); - - this.bindTexture( "guis/craftAmt.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + super.actionPerformed( btn ); try { - Long.parseLong( this.amountToCraft.getText() ); - this.next.enabled = this.amountToCraft.getText().length() > 0; + + if( btn == this.originalGuiBtn ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); + } + + if( btn == this.next ) + { + NetworkHandler.instance.sendToServer( new PacketCraftRequest( Integer.parseInt( this.amountToCraft.getText() ), isShiftKeyDown() ) ); + } } - catch (NumberFormatException e) + catch( NumberFormatException e ) { - this.next.enabled = false; + // nope.. + this.amountToCraft.setText( "1" ); } - this.amountToCraft.drawTextBox(); + boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + + if( isPlus || isMinus ) + this.addQty( this.getQty( btn ) ); + } + + private void addQty( int i ) + { + try + { + String out = this.amountToCraft.getText(); + + boolean fixed = false; + while( out.startsWith( "0" ) && out.length() > 1 ) + { + out = out.substring( 1 ); + fixed = true; + } + + if( fixed ) + this.amountToCraft.setText( out ); + + if( out.length() == 0 ) + out = "0"; + + long result = Integer.parseInt( out ); + + if( result == 1 && i > 1 ) + result = 0; + + result += i; + if( result < 1 ) + result = 1; + + out = Long.toString( result ); + Integer.parseInt( out ); + this.amountToCraft.setText( out ); + } + catch( NumberFormatException e ) + { + // :P + } } protected String getBackground() { return "guis/craftAmt.png"; } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( GuiText.SelectAmount.getLocal(), 8, 6, 4210752 ); - } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java b/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java index 2cda2c398..bc11251c4 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java @@ -26,8 +26,6 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; -import com.google.common.base.Joiner; - import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; @@ -35,6 +33,8 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; +import com.google.common.base.Joiner; + import appeng.api.AEApi; import appeng.api.storage.ITerminalHost; import appeng.api.storage.data.IAEItemStack; @@ -54,6 +54,7 @@ import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartTerminal; import appeng.util.Platform; + public class GuiCraftConfirm extends AEBaseGui { @@ -68,18 +69,13 @@ public class GuiCraftConfirm extends AEBaseGui final List visual = new ArrayList(); GuiBridge OriginalGui; + GuiButton cancel; + GuiButton start; + GuiButton selectCPU; + int tooltip = -1; - boolean isAutoStart() + public GuiCraftConfirm( InventoryPlayer inventoryPlayer, ITerminalHost te ) { - return ((ContainerCraftConfirm) this.inventorySlots).autoStart; - } - - boolean isSimulation() - { - return ((ContainerCraftConfirm) this.inventorySlots).simulation; - } - - public GuiCraftConfirm(InventoryPlayer inventoryPlayer, ITerminalHost te) { super( new ContainerCraftConfirm( inventoryPlayer, te ) ); this.xSize = 238; this.ySize = 206; @@ -87,23 +83,23 @@ public class GuiCraftConfirm extends AEBaseGui this.ccc = (ContainerCraftConfirm) this.inventorySlots; - if ( te instanceof WirelessTerminalGuiObject ) + if( te instanceof WirelessTerminalGuiObject ) this.OriginalGui = GuiBridge.GUI_WIRELESS_TERM; - if ( te instanceof PartTerminal ) + if( te instanceof PartTerminal ) this.OriginalGui = GuiBridge.GUI_ME; - if ( te instanceof PartCraftingTerminal ) + if( te instanceof PartCraftingTerminal ) this.OriginalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - if ( te instanceof PartPatternTerminal ) + if( te instanceof PartPatternTerminal ) this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } - GuiButton cancel; - GuiButton start; - GuiButton selectCPU; + boolean isAutoStart() + { + return ( (ContainerCraftConfirm) this.inventorySlots ).autoStart; + } @Override public void initGui() @@ -114,248 +110,50 @@ public class GuiCraftConfirm extends AEBaseGui this.start.enabled = false; this.buttonList.add( this.start ); - this.selectCPU = new GuiButton( 0, this.guiLeft + (219 - 180) / 2, this.guiTop + this.ySize - 68, 180, 20, GuiText.CraftingCPU.getLocal() + ": " - + GuiText.Automatic ); + this.selectCPU = new GuiButton( 0, this.guiLeft + ( 219 - 180 ) / 2, this.guiTop + this.ySize - 68, 180, 20, GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic ); this.selectCPU.enabled = false; this.buttonList.add( this.selectCPU ); - if ( this.OriginalGui != null ) + if( this.OriginalGui != null ) this.cancel = new GuiButton( 0, this.guiLeft + 6, this.guiTop + this.ySize - 25, 50, 20, GuiText.Cancel.getLocal() ); this.buttonList.add( this.cancel ); } - private void updateCPUButtonText() - { - String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); - if ( this.ccc.selectedCpu >= 0 )// && status.selectedCpu < status.cpus.size() ) - { - if ( this.ccc.myName.length() > 0 ) - { - String name = this.ccc.myName.substring( 0, Math.min( 20, this.ccc.myName.length() ) ); - btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; - } - else - btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.selectedCpu; - } - - if ( this.ccc.noCPU ) - btnTextText = GuiText.NoCraftingCPUs.getLocal(); - - this.selectCPU.displayString = btnTextText; - } - @Override - protected void actionPerformed(GuiButton btn) - { - super.actionPerformed( btn ); - - boolean backwards = Mouse.isButtonDown( 1 ); - - if ( btn == this.selectCPU ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Cpu", backwards ? "Prev" : "Next" ) ); - } - catch (IOException e) - { - AELog.error( e ); - } - } - - if ( btn == this.cancel ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); - } - - if ( btn == this.start ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Start", "Start" ) ); - } - catch (Throwable e) - { - AELog.error( e ); - } - } - - } - - private long getTotal(IAEItemStack is) - { - IAEItemStack a = this.storage.findPrecise( is ); - IAEItemStack c = this.pending.findPrecise( is ); - IAEItemStack m = this.missing.findPrecise( is ); - - long total = 0; - - if ( a != null ) - total += a.getStackSize(); - - if ( c != null ) - total += c.getStackSize(); - - if ( m != null ) - total += m.getStackSize(); - - return total; - } - - public void postUpdate(List list, byte ref) - { - switch (ref) - { - case 0: - for (IAEItemStack l : list) - this.handleInput( this.storage, l ); - break; - - case 1: - for (IAEItemStack l : list) - this.handleInput( this.pending, l ); - break; - - case 2: - for (IAEItemStack l : list) - this.handleInput( this.missing, l ); - break; - } - - for (IAEItemStack l : list) - { - long amt = this.getTotal( l ); - - if ( amt <= 0 ) - this.deleteVisualStack( l ); - else - { - IAEItemStack is = this.findVisualStack( l ); - is.setStackSize( amt ); - } - } - - this.setScrollBar(); - } - - private void handleInput(IItemList s, IAEItemStack l) - { - IAEItemStack a = s.findPrecise( l ); - - if ( l.getStackSize() <= 0 ) - { - if ( a != null ) - a.reset(); - } - else - { - if ( a == null ) - { - s.add( l.copy() ); - a = s.findPrecise( l ); - } - - if ( a != null ) - a.setStackSize( l.getStackSize() ); - } - } - - private IAEItemStack findVisualStack(IAEItemStack l) - { - for (IAEItemStack o : this.visual) - { - if ( o.equals( l ) ) - { - return o; - } - } - - IAEItemStack stack = l.copy(); - this.visual.add( stack ); - return stack; - } - - private void deleteVisualStack(IAEItemStack l) - { - Iterator i = this.visual.iterator(); - while (i.hasNext()) - { - IAEItemStack o = i.next(); - if ( o.equals( l ) ) - { - i.remove(); - return; - } - } - } - - private void setScrollBar() - { - int size = this.visual.size(); - - this.myScrollBar.setTop( 19 ).setLeft( 218 ).setHeight( 114 ); - this.myScrollBar.setRange( 0, (size + 2) / 3 - this.rows, 1 ); - } - - @Override - protected void keyTyped(char character, int key) - { - if ( !this.checkHotbarKeys( key ) ) - { - if ( key == 28 ) - { - this.actionPerformed( this.start ); - } - super.keyTyped( character, key ); - } - } - - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.setScrollBar(); - this.bindTexture( "guis/craftingreport.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - int tooltip = -1; - - @Override - public void drawScreen(int mouse_x, int mouse_y, float btn) + public void drawScreen( int mouse_x, int mouse_y, float btn ) { this.updateCPUButtonText(); - this.start.enabled = !(this.ccc.noCPU || this.isSimulation()); + this.start.enabled = !( this.ccc.noCPU || this.isSimulation() ); this.selectCPU.enabled = !this.isSimulation(); int x = 0; int y = 0; - int gx = (this.width - this.xSize) / 2; - int gy = (this.height - this.ySize) / 2; + int gx = ( this.width - this.xSize ) / 2; + int gy = ( this.height - this.ySize ) / 2; int offY = 23; this.tooltip = -1; - for (int z = 0; z <= 4 * 5; z++) + for( int z = 0; z <= 4 * 5; z++ ) { int minX = gx + 9 + x * 67; int minY = gy + 22 + y * offY; - if ( minX < mouse_x && minX + 67 > mouse_x ) + if( minX < mouse_x && minX + 67 > mouse_x ) { - if ( minY < mouse_y && minY + offY - 2 > mouse_y ) + if( minY < mouse_y && minY + offY - 2 > mouse_y ) { this.tooltip = z; break; } - } x++; - if ( x > 2 ) + if( x > 2 ) { y++; x = 0; @@ -365,23 +163,47 @@ public class GuiCraftConfirm extends AEBaseGui super.drawScreen( mouse_x, mouse_y, btn ); } + private void updateCPUButtonText() + { + String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); + if( this.ccc.selectedCpu >= 0 )// && status.selectedCpu < status.cpus.size() ) + { + if( this.ccc.myName.length() > 0 ) + { + String name = this.ccc.myName.substring( 0, Math.min( 20, this.ccc.myName.length() ) ); + btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; + } + else + btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.selectedCpu; + } + + if( this.ccc.noCPU ) + btnTextText = GuiText.NoCraftingCPUs.getLocal(); + + this.selectCPU.displayString = btnTextText; + } + + boolean isSimulation() + { + return ( (ContainerCraftConfirm) this.inventorySlots ).simulation; + } + @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { long BytesUsed = this.ccc.bytesUsed; String byteUsed = NumberFormat.getInstance().format( BytesUsed ); - String Add = BytesUsed > 0 ? (byteUsed + ' ' + GuiText.BytesUsed.getLocal()) : GuiText.CalculatingWait.getLocal(); + String Add = BytesUsed > 0 ? ( byteUsed + ' ' + GuiText.BytesUsed.getLocal() ) : GuiText.CalculatingWait.getLocal(); this.fontRendererObj.drawString( GuiText.CraftingPlan.getLocal() + " - " + Add, 8, 7, 4210752 ); String dsp = null; - if ( this.isSimulation() ) + if( this.isSimulation() ) dsp = GuiText.Simulation.getLocal(); else - dsp = this.ccc.cpuBytesAvail > 0 ? (GuiText.Bytes.getLocal() + ": " + this.ccc.cpuBytesAvail + " : " + GuiText.CoProcessors.getLocal() + ": " + this.ccc.cpuCoProcessors) - : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A"; + dsp = this.ccc.cpuBytesAvail > 0 ? ( GuiText.Bytes.getLocal() + ": " + this.ccc.cpuBytesAvail + " : " + GuiText.CoProcessors.getLocal() + ": " + this.ccc.cpuCoProcessors ) : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A"; - int offset = (219 - this.fontRendererObj.getStringWidth( dsp )) / 2; + int offset = ( 219 - this.fontRendererObj.getStringWidth( dsp ) ) / 2; this.fontRendererObj.drawString( dsp, offset, 165, 4210752 ); int sectionLength = 67; @@ -400,10 +222,10 @@ public class GuiCraftConfirm extends AEBaseGui int offY = 23; - for (int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++) + for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) { IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); - if ( refStack != null ) + if( refStack != null ) { GL11.glPushMatrix(); GL11.glScaled( 0.5, 0.5, 0.5 ); @@ -414,118 +236,284 @@ public class GuiCraftConfirm extends AEBaseGui int lines = 0; - if ( stored != null && stored.getStackSize() > 0 ) + if( stored != null && stored.getStackSize() > 0 ) lines++; - if ( pendingStack != null && pendingStack.getStackSize() > 0 ) + if( pendingStack != null && pendingStack.getStackSize() > 0 ) lines++; - if ( pendingStack != null && pendingStack.getStackSize() > 0 ) + if( pendingStack != null && pendingStack.getStackSize() > 0 ) lines++; - int negY = ((lines - 1) * 5) / 2; + int negY = ( ( lines - 1 ) * 5 ) / 2; int downY = 0; boolean red = false; - if ( stored != null && stored.getStackSize() > 0 ) + if( stored != null && stored.getStackSize() > 0 ) { String str = Long.toString( stored.getStackSize() ); - if ( stored.getStackSize() >= 10000 ) + if( stored.getStackSize() >= 10000 ) str = Long.toString( stored.getStackSize() / 1000 ) + 'k'; - if ( stored.getStackSize() >= 10000000 ) + if( stored.getStackSize() >= 10000000 ) str = Long.toString( stored.getStackSize() / 1000000 ) + 'm'; str = GuiText.FromStorage.getLocal() + ": " + str; int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), (y * offY + yo - + 6 - negY + downY) * 2, 4210752 ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) lineList.add( GuiText.FromStorage.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); downY += 5; } - if ( missingStack != null && missingStack.getStackSize() > 0 ) + if( missingStack != null && missingStack.getStackSize() > 0 ) { String str = Long.toString( missingStack.getStackSize() ); - if ( missingStack.getStackSize() >= 10000 ) + if( missingStack.getStackSize() >= 10000 ) str = Long.toString( missingStack.getStackSize() / 1000 ) + 'k'; - if ( missingStack.getStackSize() >= 10000000 ) + if( missingStack.getStackSize() >= 10000000 ) str = Long.toString( missingStack.getStackSize() / 1000000 ) + 'm'; str = GuiText.Missing.getLocal() + ": " + str; int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), (y * offY + yo - + 6 - negY + downY) * 2, 4210752 ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) lineList.add( GuiText.Missing.getLocal() + ": " + Long.toString( missingStack.getStackSize() ) ); red = true; downY += 5; } - if ( pendingStack != null && pendingStack.getStackSize() > 0 ) + if( pendingStack != null && pendingStack.getStackSize() > 0 ) { String str = Long.toString( pendingStack.getStackSize() ); - if ( pendingStack.getStackSize() >= 10000 ) + if( pendingStack.getStackSize() >= 10000 ) str = Long.toString( pendingStack.getStackSize() / 1000 ) + 'k'; - if ( pendingStack.getStackSize() >= 10000000 ) + if( pendingStack.getStackSize() >= 10000000 ) str = Long.toString( pendingStack.getStackSize() / 1000000 ) + 'm'; str = GuiText.ToCraft.getLocal() + ": " + str; int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), (y * offY + yo - + 6 - negY + downY) * 2, 4210752 ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) lineList.add( GuiText.ToCraft.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); - } GL11.glPopMatrix(); - int posX = x * (1 + sectionLength) + xo + sectionLength - 19; + int posX = x * ( 1 + sectionLength ) + xo + sectionLength - 19; int posY = y * offY + yo; ItemStack is = refStack.copy().getItemStack(); - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) { dspToolTip = Platform.getItemDisplayName( is ); - if ( lineList.size() > 0 ) + if( lineList.size() > 0 ) dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); - toolPosX = x * (1 + sectionLength) + xo + sectionLength - 8; + toolPosX = x * ( 1 + sectionLength ) + xo + sectionLength - 8; toolPosY = y * offY + yo; } this.drawItem( posX, posY, is ); - if ( red ) + if( red ) { - int startX = x * (1 + sectionLength) + xo; + int startX = x * ( 1 + sectionLength ) + xo; int startY = posY - 4; drawRect( startX, startY, startX + sectionLength, startY + offY, 0x1AFF0000 ); } x++; - if ( x > 2 ) + if( x > 2 ) { y++; x = 0; } } - } - if ( this.tooltip >= 0 && dspToolTip.length() > 0 ) + if( this.tooltip >= 0 && dspToolTip.length() > 0 ) { GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); this.drawTooltip( toolPosX, toolPosY + 10, 0, dspToolTip ); GL11.glPopAttrib(); } - } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.setScrollBar(); + this.bindTexture( "guis/craftingreport.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } + + private void setScrollBar() + { + int size = this.visual.size(); + + this.myScrollBar.setTop( 19 ).setLeft( 218 ).setHeight( 114 ); + this.myScrollBar.setRange( 0, ( size + 2 ) / 3 - this.rows, 1 ); + } + + public void postUpdate( List list, byte ref ) + { + switch( ref ) + { + case 0: + for( IAEItemStack l : list ) + this.handleInput( this.storage, l ); + break; + + case 1: + for( IAEItemStack l : list ) + this.handleInput( this.pending, l ); + break; + + case 2: + for( IAEItemStack l : list ) + this.handleInput( this.missing, l ); + break; + } + + for( IAEItemStack l : list ) + { + long amt = this.getTotal( l ); + + if( amt <= 0 ) + this.deleteVisualStack( l ); + else + { + IAEItemStack is = this.findVisualStack( l ); + is.setStackSize( amt ); + } + } + + this.setScrollBar(); + } + + private void handleInput( IItemList s, IAEItemStack l ) + { + IAEItemStack a = s.findPrecise( l ); + + if( l.getStackSize() <= 0 ) + { + if( a != null ) + a.reset(); + } + else + { + if( a == null ) + { + s.add( l.copy() ); + a = s.findPrecise( l ); + } + + if( a != null ) + a.setStackSize( l.getStackSize() ); + } + } + + private long getTotal( IAEItemStack is ) + { + IAEItemStack a = this.storage.findPrecise( is ); + IAEItemStack c = this.pending.findPrecise( is ); + IAEItemStack m = this.missing.findPrecise( is ); + + long total = 0; + + if( a != null ) + total += a.getStackSize(); + + if( c != null ) + total += c.getStackSize(); + + if( m != null ) + total += m.getStackSize(); + + return total; + } + + private void deleteVisualStack( IAEItemStack l ) + { + Iterator i = this.visual.iterator(); + while( i.hasNext() ) + { + IAEItemStack o = i.next(); + if( o.equals( l ) ) + { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack( IAEItemStack l ) + { + for( IAEItemStack o : this.visual ) + { + if( o.equals( l ) ) + { + return o; + } + } + + IAEItemStack stack = l.copy(); + this.visual.add( stack ); + return stack; + } + + @Override + protected void keyTyped( char character, int key ) + { + if( !this.checkHotbarKeys( key ) ) + { + if( key == 28 ) + { + this.actionPerformed( this.start ); + } + super.keyTyped( character, key ); + } + } + + @Override + protected void actionPerformed( GuiButton btn ) + { + super.actionPerformed( btn ); + + boolean backwards = Mouse.isButtonDown( 1 ); + + if( btn == this.selectCPU ) + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Cpu", backwards ? "Prev" : "Next" ) ); + } + catch( IOException e ) + { + AELog.error( e ); + } + } + + if( btn == this.cancel ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); + } + + if( btn == this.start ) + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Start", "Start" ) ); + } + catch( Throwable e ) + { + AELog.error( e ); + } + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java index a478026c5..437abbdcf 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java @@ -51,6 +51,7 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; import appeng.util.Platform; + public class GuiCraftingCPU extends AEBaseGui implements ISortSource { @@ -61,6 +62,21 @@ public class GuiCraftingCPU extends AEBaseGui implements ISortSource IItemList pending = AEApi.instance().storage().createItemList(); List visual = new ArrayList(); + GuiButton cancel; + int tooltip = -1; + + public GuiCraftingCPU( InventoryPlayer inventoryPlayer, Object te ) + { + this( new ContainerCraftingCPU( inventoryPlayer, te ) ); + } + + protected GuiCraftingCPU( ContainerCraftingCPU container ) + { + super( container ); + this.ySize = 184; + this.xSize = 238; + this.myScrollBar = new GuiScrollbar(); + } public void clearItems() { @@ -70,31 +86,18 @@ public class GuiCraftingCPU extends AEBaseGui implements ISortSource this.visual = new ArrayList(); } - protected GuiCraftingCPU(ContainerCraftingCPU container) { - super( container ); - this.ySize = 184; - this.xSize = 238; - this.myScrollBar = new GuiScrollbar(); - } - - public GuiCraftingCPU(InventoryPlayer inventoryPlayer, Object te) { - this( new ContainerCraftingCPU( inventoryPlayer, te ) ); - } - - GuiButton cancel; - @Override - protected void actionPerformed(GuiButton btn) + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); - if ( this.cancel == btn ) + if( this.cancel == btn ) { try { NetworkHandler.instance.sendToServer( new PacketValueConfig( "TileCrafting.Cancel", "Cancel" ) ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } @@ -110,162 +113,45 @@ public class GuiCraftingCPU extends AEBaseGui implements ISortSource this.buttonList.add( this.cancel ); } - private long getTotal(IAEItemStack is) - { - IAEItemStack a = this.storage.findPrecise( is ); - IAEItemStack b = this.active.findPrecise( is ); - IAEItemStack c = this.pending.findPrecise( is ); - - long total = 0; - - if ( a != null ) - total += a.getStackSize(); - - if ( b != null ) - total += b.getStackSize(); - - if ( c != null ) - total += c.getStackSize(); - - return total; - } - - public void postUpdate(List list, byte ref) - { - switch (ref) - { - case 0: - for (IAEItemStack l : list) - this.handleInput( this.storage, l ); - break; - - case 1: - for (IAEItemStack l : list) - this.handleInput( this.active, l ); - break; - - case 2: - for (IAEItemStack l : list) - this.handleInput( this.pending, l ); - break; - } - - for (IAEItemStack l : list) - { - long amt = this.getTotal( l ); - - if ( amt <= 0 ) - this.deleteVisualStack( l ); - else - { - IAEItemStack is = this.findVisualStack( l ); - is.setStackSize( amt ); - } - } - - this.setScrollBar(); - } - - private void handleInput(IItemList s, IAEItemStack l) - { - IAEItemStack a = s.findPrecise( l ); - - if ( l.getStackSize() <= 0 ) - { - if ( a != null ) - a.reset(); - } - else - { - if ( a == null ) - { - s.add( l.copy() ); - a = s.findPrecise( l ); - } - - if ( a != null ) - a.setStackSize( l.getStackSize() ); - } - } - - private IAEItemStack findVisualStack(IAEItemStack l) - { - for (IAEItemStack o : this.visual) - { - if ( o.equals( l ) ) - { - return o; - } - } - - IAEItemStack stack = l.copy(); - this.visual.add( stack ); - return stack; - } - - private void deleteVisualStack(IAEItemStack l) - { - Iterator i = this.visual.iterator(); - while (i.hasNext()) - { - IAEItemStack o = i.next(); - if ( o.equals( l ) ) - { - i.remove(); - return; - } - } - } - private void setScrollBar() { int size = this.visual.size(); this.myScrollBar.setTop( 19 ).setLeft( 218 ).setHeight( 137 ); - this.myScrollBar.setRange( 0, (size + 2) / 3 - this.rows, 1 ); + this.myScrollBar.setRange( 0, ( size + 2 ) / 3 - this.rows, 1 ); } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/craftingcpu.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - int tooltip = -1; - - @Override - public void drawScreen(int mouse_x, int mouse_y, float btn) + public void drawScreen( int mouse_x, int mouse_y, float btn ) { this.cancel.enabled = !this.visual.isEmpty(); int x = 0; int y = 0; - int gx = (this.width - this.xSize) / 2; - int gy = (this.height - this.ySize) / 2; + int gx = ( this.width - this.xSize ) / 2; + int gy = ( this.height - this.ySize ) / 2; int offY = 23; this.tooltip = -1; - for (int z = 0; z <= 4 * 5; z++) + for( int z = 0; z <= 4 * 5; z++ ) { int minX = gx + 9 + x * 67; int minY = gy + 22 + y * offY; - if ( minX < mouse_x && minX + 67 > mouse_x ) + if( minX < mouse_x && minX + 67 > mouse_x ) { - if ( minY < mouse_y && minY + offY - 2 > mouse_y ) + if( minY < mouse_y && minY + offY - 2 > mouse_y ) { this.tooltip = z; break; } - } x++; - if ( x > 2 ) + if( x > 2 ) { y++; x = 0; @@ -276,7 +162,7 @@ public class GuiCraftingCPU extends AEBaseGui implements ISortSource } @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.CraftingStatus.getLocal() ), 8, 7, 4210752 ); @@ -296,10 +182,10 @@ public class GuiCraftingCPU extends AEBaseGui implements ISortSource int offY = 23; - for (int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++) + for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) { IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); - if ( refStack != null ) + if( refStack != null ) { GL11.glPushMatrix(); GL11.glScaled( 0.5, 0.5, 0.5 ); @@ -312,102 +198,98 @@ public class GuiCraftingCPU extends AEBaseGui implements ISortSource boolean active = false; boolean scheduled = false; - if ( stored != null && stored.getStackSize() > 0 ) + if( stored != null && stored.getStackSize() > 0 ) { lines++; } - if ( activeStack != null && activeStack.getStackSize() > 0 ) + if( activeStack != null && activeStack.getStackSize() > 0 ) { lines++; active = true; } - if ( pendingStack != null && pendingStack.getStackSize() > 0 ) + if( pendingStack != null && pendingStack.getStackSize() > 0 ) { lines++; scheduled = true; } - if ( AEConfig.instance.useColoredCraftingStatus && ( active || scheduled ) ) + if( AEConfig.instance.useColoredCraftingStatus && ( active || scheduled ) ) { int bgColor = ( active ? AEColor.Green.blackVariant : AEColor.Yellow.blackVariant ) | 0x5A000000; - int startX = (x * (1 + sectionLength) + xo) * 2; - int startY = ((y * offY + yo) - 3) * 2; - drawRect( startX, startY, startX + (sectionLength * 2), startY + (offY * 2) - 2, bgColor); + int startX = ( x * ( 1 + sectionLength ) + xo ) * 2; + int startY = ( ( y * offY + yo ) - 3 ) * 2; + drawRect( startX, startY, startX + ( sectionLength * 2 ), startY + ( offY * 2 ) - 2, bgColor ); } - int negY = ((lines - 1) * 5) / 2; + int negY = ( ( lines - 1 ) * 5 ) / 2; int downY = 0; - if ( stored != null && stored.getStackSize() > 0 ) + if( stored != null && stored.getStackSize() > 0 ) { String str = Long.toString( stored.getStackSize() ); - if ( stored.getStackSize() >= 10000 ) + if( stored.getStackSize() >= 10000 ) str = Long.toString( stored.getStackSize() / 1000 ) + 'k'; - if ( stored.getStackSize() >= 10000000 ) + if( stored.getStackSize() >= 10000000 ) str = Long.toString( stored.getStackSize() / 1000000 ) + 'm'; str = GuiText.Stored.getLocal() + ": " + str; int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), (y * offY + yo - + 6 - negY + downY) * 2, 4210752 ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) lineList.add( GuiText.Stored.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); downY += 5; } - if ( activeStack != null && activeStack.getStackSize() > 0 ) + if( activeStack != null && activeStack.getStackSize() > 0 ) { String str = Long.toString( activeStack.getStackSize() ); - if ( activeStack.getStackSize() >= 10000 ) + if( activeStack.getStackSize() >= 10000 ) str = Long.toString( activeStack.getStackSize() / 1000 ) + 'k'; - if ( activeStack.getStackSize() >= 10000000 ) + if( activeStack.getStackSize() >= 10000000 ) str = Long.toString( activeStack.getStackSize() / 1000000 ) + 'm'; str = GuiText.Crafting.getLocal() + ": " + str; int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), (y * offY + yo - + 6 - negY + downY) * 2, 4210752 ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) lineList.add( GuiText.Crafting.getLocal() + ": " + Long.toString( activeStack.getStackSize() ) ); downY += 5; } - if ( pendingStack != null && pendingStack.getStackSize() > 0 ) + if( pendingStack != null && pendingStack.getStackSize() > 0 ) { String str = Long.toString( pendingStack.getStackSize() ); - if ( pendingStack.getStackSize() >= 10000 ) + if( pendingStack.getStackSize() >= 10000 ) str = Long.toString( pendingStack.getStackSize() / 1000 ) + 'k'; - if ( pendingStack.getStackSize() >= 10000000 ) + if( pendingStack.getStackSize() >= 10000000 ) str = Long.toString( pendingStack.getStackSize() / 1000000 ) + 'm'; str = GuiText.Scheduled.getLocal() + ": " + str; int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), (y * offY + yo - + 6 - negY + downY) * 2, 4210752 ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) lineList.add( GuiText.Scheduled.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); - } GL11.glPopMatrix(); - int posX = x * (1 + sectionLength) + xo + sectionLength - 19; + int posX = x * ( 1 + sectionLength ) + xo + sectionLength - 19; int posY = y * offY + yo; ItemStack is = refStack.copy().getItemStack(); - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) { dspToolTip = Platform.getItemDisplayName( is ); - if ( lineList.size() > 0 ) + if( lineList.size() > 0 ) dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); - toolPosX = x * (1 + sectionLength) + xo + sectionLength - 8; + toolPosX = x * ( 1 + sectionLength ) + xo + sectionLength - 8; toolPosY = y * offY + yo; } @@ -415,22 +297,134 @@ public class GuiCraftingCPU extends AEBaseGui implements ISortSource x++; - if ( x > 2 ) + if( x > 2 ) { y++; x = 0; } } - } - if ( this.tooltip >= 0 && dspToolTip.length() > 0 ) + if( this.tooltip >= 0 && dspToolTip.length() > 0 ) { GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); this.drawTooltip( toolPosX, toolPosY + 10, 0, dspToolTip ); GL11.glPopAttrib(); } + } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/craftingcpu.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } + + public void postUpdate( List list, byte ref ) + { + switch( ref ) + { + case 0: + for( IAEItemStack l : list ) + this.handleInput( this.storage, l ); + break; + + case 1: + for( IAEItemStack l : list ) + this.handleInput( this.active, l ); + break; + + case 2: + for( IAEItemStack l : list ) + this.handleInput( this.pending, l ); + break; + } + + for( IAEItemStack l : list ) + { + long amt = this.getTotal( l ); + + if( amt <= 0 ) + this.deleteVisualStack( l ); + else + { + IAEItemStack is = this.findVisualStack( l ); + is.setStackSize( amt ); + } + } + + this.setScrollBar(); + } + + private void handleInput( IItemList s, IAEItemStack l ) + { + IAEItemStack a = s.findPrecise( l ); + + if( l.getStackSize() <= 0 ) + { + if( a != null ) + a.reset(); + } + else + { + if( a == null ) + { + s.add( l.copy() ); + a = s.findPrecise( l ); + } + + if( a != null ) + a.setStackSize( l.getStackSize() ); + } + } + + private long getTotal( IAEItemStack is ) + { + IAEItemStack a = this.storage.findPrecise( is ); + IAEItemStack b = this.active.findPrecise( is ); + IAEItemStack c = this.pending.findPrecise( is ); + + long total = 0; + + if( a != null ) + total += a.getStackSize(); + + if( b != null ) + total += b.getStackSize(); + + if( c != null ) + total += c.getStackSize(); + + return total; + } + + private void deleteVisualStack( IAEItemStack l ) + { + Iterator i = this.visual.iterator(); + while( i.hasNext() ) + { + IAEItemStack o = i.next(); + if( o.equals( l ) ) + { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack( IAEItemStack l ) + { + for( IAEItemStack o : this.visual ) + { + if( o.equals( l ) ) + { + return o; + } + } + + IAEItemStack stack = l.copy(); + this.visual.add( stack ); + return stack; } @Override @@ -450,5 +444,4 @@ public class GuiCraftingCPU extends AEBaseGui implements ISortSource { return ViewItems.ALL; } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java index 4a90690c6..465973644 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java @@ -19,8 +19,10 @@ /** * */ + package appeng.client.gui.implementations; + import java.io.IOException; import org.lwjgl.input.Mouse; @@ -46,6 +48,7 @@ import appeng.parts.reporting.PartCraftingTerminal; import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartTerminal; + public class GuiCraftingStatus extends GuiCraftingCPU { @@ -56,7 +59,8 @@ public class GuiCraftingStatus extends GuiCraftingCPU GuiBridge originalGui; ItemStack myIcon = null; - public GuiCraftingStatus(InventoryPlayer inventoryPlayer, ITerminalHost te) { + public GuiCraftingStatus( InventoryPlayer inventoryPlayer, ITerminalHost te ) + { super( new ContainerCraftingStatus( inventoryPlayer, te ) ); this.status = (ContainerCraftingStatus) this.inventorySlots; @@ -64,9 +68,9 @@ public class GuiCraftingStatus extends GuiCraftingCPU final IDefinitions definitions = AEApi.instance().definitions(); final IParts parts = definitions.parts(); - if ( target instanceof WirelessTerminalGuiObject ) + if( target instanceof WirelessTerminalGuiObject ) { - for ( ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) + for( ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) { this.myIcon = wirelessTerminalStack; } @@ -74,27 +78,27 @@ public class GuiCraftingStatus extends GuiCraftingCPU this.originalGui = GuiBridge.GUI_WIRELESS_TERM; } - if ( target instanceof PartTerminal ) + if( target instanceof PartTerminal ) { - for ( ItemStack stack : parts.terminal().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.terminal().maybeStack( 1 ).asSet() ) { this.myIcon = stack; } this.originalGui = GuiBridge.GUI_ME; } - if ( target instanceof PartCraftingTerminal ) + if( target instanceof PartCraftingTerminal ) { - for ( ItemStack stack : parts.craftingTerminal().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.craftingTerminal().maybeStack( 1 ).asSet() ) { this.myIcon = stack; } this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; } - if ( target instanceof PartPatternTerminal ) + if( target instanceof PartPatternTerminal ) { - for ( ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) { this.myIcon = stack; } @@ -103,36 +107,30 @@ public class GuiCraftingStatus extends GuiCraftingCPU } @Override - protected void actionPerformed(GuiButton btn) + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); boolean backwards = Mouse.isButtonDown( 1 ); - if ( btn == this.selectCPU ) + if( btn == this.selectCPU ) { try { NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Cpu", backwards ? "Prev" : "Next" ) ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } } - if ( btn == this.originalGuiBtn ) + if( btn == this.originalGuiBtn ) { NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); } } - @Override - protected String getGuiDisplayName(String in) - { - return in; // the cup name is on the button - } - @Override public void initGui() { @@ -142,20 +140,27 @@ public class GuiCraftingStatus extends GuiCraftingCPU // selectCPU.enabled = false; this.buttonList.add( this.selectCPU ); - if ( this.myIcon != null ) + if( this.myIcon != null ) { this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 213, this.guiTop - 4, this.myIcon, this.myIcon.getDisplayName(), itemRender ) ); this.originalGuiBtn.hideEdge = 13; } } + @Override + public void drawScreen( int mouseX, int mouseY, float btn ) + { + this.updateCPUButtonText(); + super.drawScreen( mouseX, mouseY, btn ); + } + private void updateCPUButtonText() { String btnTextText = GuiText.NoCraftingJobs.getLocal(); - if ( this.status.selectedCpu >= 0 )// && status.selectedCpu < status.cpus.size() ) + if( this.status.selectedCpu >= 0 )// && status.selectedCpu < status.cpus.size() ) { - if ( this.status.myName.length() > 0 ) + if( this.status.myName.length() > 0 ) { String name = this.status.myName.substring( 0, Math.min( 20, this.status.myName.length() ) ); btnTextText = GuiText.CPUs.getLocal() + ": " + name; @@ -164,16 +169,15 @@ public class GuiCraftingStatus extends GuiCraftingCPU btnTextText = GuiText.CPUs.getLocal() + ": #" + this.status.selectedCpu; } - if ( this.status.noCPU ) + if( this.status.noCPU ) btnTextText = GuiText.NoCraftingJobs.getLocal(); this.selectCPU.displayString = btnTextText; } @Override - public void drawScreen(int mouseX, int mouseY, float btn) + protected String getGuiDisplayName( String in ) { - this.updateCPUButtonText(); - super.drawScreen( mouseX, mouseY, btn ); + return in; // the cup name is on the button } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java index d3f92cbc7..99626433d 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; @@ -34,11 +35,42 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInventoryAction; import appeng.helpers.InventoryAction; + public class GuiCraftingTerm extends GuiMEMonitorable { GuiImgButton clearBtn; + public GuiCraftingTerm( InventoryPlayer inventoryPlayer, ITerminalHost te ) + { + super( inventoryPlayer, te, new ContainerCraftingTerm( inventoryPlayer, te ) ); + this.reservedSpace = 73; + } + + @Override + protected void actionPerformed( GuiButton btn ) + { + super.actionPerformed( btn ); + + if( this.clearBtn == btn ) + { + Slot s = null; + Container c = this.inventorySlots; + for( Object j : c.inventorySlots ) + { + if( j instanceof SlotCraftingMatrix ) + s = (Slot) j; + } + + if( s != null ) + { + PacketInventoryAction p; + p = new PacketInventoryAction( InventoryAction.MOVE_REGION, s.slotNumber, 0 ); + NetworkHandler.instance.sendToServer( p ); + } + } + } + @Override public void initGui() { @@ -48,32 +80,10 @@ public class GuiCraftingTerm extends GuiMEMonitorable } @Override - protected void actionPerformed(GuiButton btn) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - super.actionPerformed( btn ); - - if ( this.clearBtn == btn ) - { - Slot s = null; - Container c = this.inventorySlots; - for (Object j : c.inventorySlots) - { - if ( j instanceof SlotCraftingMatrix ) - s = (Slot) j; - } - - if ( s != null ) - { - PacketInventoryAction p; - p = new PacketInventoryAction( InventoryAction.MOVE_REGION, s.slotNumber, 0 ); - NetworkHandler.instance.sendToServer( p ); - } - } - } - - public GuiCraftingTerm(InventoryPlayer inventoryPlayer, ITerminalHost te) { - super( inventoryPlayer, te, new ContainerCraftingTerm( inventoryPlayer, te ) ); - this.reservedSpace = 73; + super.drawFG( offsetX, offsetY, mouseX, mouseY ); + this.fontRendererObj.drawString( GuiText.CraftingTerminal.getLocal(), 8, this.ySize - 96 + 1 - this.reservedSpace, 4210752 ); } @Override @@ -81,12 +91,4 @@ public class GuiCraftingTerm extends GuiMEMonitorable { return "guis/crafting.png"; } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.CraftingTerminal.getLocal(), 8, this.ySize - 96 + 1 - this.reservedSpace, 4210752 ); - } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiDrive.java b/src/main/java/appeng/client/gui/implementations/GuiDrive.java index a2d87fcc7..3beeb59b5 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiDrive.java +++ b/src/main/java/appeng/client/gui/implementations/GuiDrive.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; @@ -30,17 +31,24 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.tile.storage.TileDrive; + public class GuiDrive extends AEBaseGui { GuiTabButton priority; + public GuiDrive( InventoryPlayer inventoryPlayer, TileDrive te ) + { + super( new ContainerDrive( inventoryPlayer, te ) ); + this.ySize = 199; + } + @Override - protected void actionPerformed(GuiButton par1GuiButton) + protected void actionPerformed( GuiButton par1GuiButton ) { super.actionPerformed( par1GuiButton ); - if ( par1GuiButton == this.priority ) + if( par1GuiButton == this.priority ) { NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); } @@ -54,23 +62,17 @@ public class GuiDrive extends AEBaseGui this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); } - public GuiDrive(InventoryPlayer inventoryPlayer, TileDrive te) { - super( new ContainerDrive( inventoryPlayer, te ) ); - this.ySize = 199; - } - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/drive.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Drive.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/drive.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java b/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java index f836a1a01..6d839c9b0 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java +++ b/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java @@ -50,19 +50,6 @@ public class GuiFormationPlane extends GuiUpgradeable this.ySize = 251; } - @Override - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.FormationPlane.getLocal() ), 8, 6, 4210752 ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - - if ( this.fuzzyMode != null ) - this.fuzzyMode.set( this.cvb.fzMode ); - - if ( this.placeMode != null ) - this.placeMode.set( ( ( ContainerFormationPlane ) this.cvb ).placeMode ); - } - @Override protected void addButtons() { @@ -76,21 +63,16 @@ public class GuiFormationPlane extends GuiUpgradeable } @Override - protected void actionPerformed( GuiButton btn ) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - super.actionPerformed( btn ); + this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.FormationPlane.getLocal() ), 8, 6, 4210752 ); + this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - boolean backwards = Mouse.isButtonDown( 1 ); - - if ( btn == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - else if ( btn == this.placeMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.placeMode.getSetting(), backwards ) ); - } + if( this.fuzzyMode != null ) + this.fuzzyMode.set( this.cvb.fzMode ); + if( this.placeMode != null ) + this.placeMode.set( ( (ContainerFormationPlane) this.cvb ).placeMode ); } @Override @@ -99,4 +81,20 @@ public class GuiFormationPlane extends GuiUpgradeable return "guis/storagebus.png"; } + @Override + protected void actionPerformed( GuiButton btn ) + { + super.actionPerformed( btn ); + + boolean backwards = Mouse.isButtonDown( 1 ); + + if( btn == this.priority ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); + } + else if( btn == this.placeMode ) + { + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.placeMode.getSetting(), backwards ) ); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiGrinder.java b/src/main/java/appeng/client/gui/implementations/GuiGrinder.java index a3a28162a..2136dc887 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiGrinder.java +++ b/src/main/java/appeng/client/gui/implementations/GuiGrinder.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.client.gui.AEBaseGui; @@ -25,26 +26,27 @@ import appeng.container.implementations.ContainerGrinder; import appeng.core.localization.GuiText; import appeng.tile.grindstone.TileGrinder; + public class GuiGrinder extends AEBaseGui { - public GuiGrinder(InventoryPlayer inventoryPlayer, TileGrinder te) { + public GuiGrinder( InventoryPlayer inventoryPlayer, TileGrinder te ) + { super( new ContainerGrinder( inventoryPlayer, te ) ); this.ySize = 176; } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/grinder.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.GrindStone.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/grinder.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiIOPort.java b/src/main/java/appeng/client/gui/implementations/GuiIOPort.java index acf6acab6..28ce0c9d4 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiIOPort.java +++ b/src/main/java/appeng/client/gui/implementations/GuiIOPort.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import org.lwjgl.input.Mouse; import net.minecraft.client.gui.GuiButton; @@ -37,51 +38,19 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.tile.storage.TileIOPort; + public class GuiIOPort extends GuiUpgradeable { GuiImgButton fullMode; GuiImgButton operationMode; - public GuiIOPort(InventoryPlayer inventoryPlayer, TileIOPort te) { + public GuiIOPort( InventoryPlayer inventoryPlayer, TileIOPort te ) + { super( new ContainerIOPort( inventoryPlayer, te ) ); this.ySize = 166; } - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - - final IDefinitions definitions = AEApi.instance().definitions(); - - for ( ItemStack cell1kStack : definitions.items().cell1k().maybeStack( 1 ).asSet() ) - { - this.drawItem( offsetX + 66 - 8, offsetY + 17, cell1kStack ); - } - - for ( ItemStack driveStack : definitions.blocks().drive().maybeStack( 1 ).asSet() ) - { - this.drawItem( offsetX + 94 + 8, offsetY + 17, driveStack ); - } - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.IOPort.getLocal() ), 8, 6, 4210752 ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - - if ( this.redstoneMode != null ) - this.redstoneMode.set( this.cvb.rsMode ); - - if ( this.operationMode != null ) - this.operationMode.set( ((ContainerIOPort) this.cvb).opMode ); - - if ( this.fullMode != null ) - this.fullMode.set( ((ContainerIOPort) this.cvb).fMode ); - } - @Override protected void addButtons() { @@ -95,17 +64,37 @@ public class GuiIOPort extends GuiUpgradeable } @Override - protected void actionPerformed(GuiButton btn) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - super.actionPerformed( btn ); + this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.IOPort.getLocal() ), 8, 6, 4210752 ); + this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - boolean backwards = Mouse.isButtonDown( 1 ); + if( this.redstoneMode != null ) + this.redstoneMode.set( this.cvb.rsMode ); - if ( btn == this.fullMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.fullMode.getSetting(), backwards ) ); + if( this.operationMode != null ) + this.operationMode.set( ( (ContainerIOPort) this.cvb ).opMode ); - if ( btn == this.operationMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.operationMode.getSetting(), backwards ) ); + if( this.fullMode != null ) + this.fullMode.set( ( (ContainerIOPort) this.cvb ).fMode ); + } + + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + super.drawBG( offsetX, offsetY, mouseX, mouseY ); + + final IDefinitions definitions = AEApi.instance().definitions(); + + for( ItemStack cell1kStack : definitions.items().cell1k().maybeStack( 1 ).asSet() ) + { + this.drawItem( offsetX + 66 - 8, offsetY + 17, cell1kStack ); + } + + for( ItemStack driveStack : definitions.blocks().drive().maybeStack( 1 ).asSet() ) + { + this.drawItem( offsetX + 94 + 8, offsetY + 17, driveStack ); + } } @Override @@ -114,4 +103,17 @@ public class GuiIOPort extends GuiUpgradeable return "guis/ioport.png"; } + @Override + protected void actionPerformed( GuiButton btn ) + { + super.actionPerformed( btn ); + + boolean backwards = Mouse.isButtonDown( 1 ); + + if( btn == this.fullMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.fullMode.getSetting(), backwards ) ); + + if( btn == this.operationMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.operationMode.getSetting(), backwards ) ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInscriber.java b/src/main/java/appeng/client/gui/implementations/GuiInscriber.java index b51263810..56e30fe0d 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInscriber.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInscriber.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.client.gui.AEBaseGui; @@ -28,13 +29,14 @@ import appeng.container.implementations.ContainerUpgradeable; import appeng.core.localization.GuiText; import appeng.tile.misc.TileInscriber; + public class GuiInscriber extends AEBaseGui { final ContainerInscriber cvc; GuiProgressBar pb; - public GuiInscriber(InventoryPlayer inventoryPlayer, TileInscriber te) + public GuiInscriber( InventoryPlayer inventoryPlayer, TileInscriber te ) { super( new ContainerInscriber( inventoryPlayer, te ) ); this.cvc = (ContainerInscriber) this.inventorySlots; @@ -42,32 +44,22 @@ public class GuiInscriber extends AEBaseGui this.xSize = this.hasToolbox() ? 246 : 211; } + protected boolean hasToolbox() + { + return ( (ContainerUpgradeable) this.inventorySlots ).hasToolbox(); + } + @Override public void initGui() { super.initGui(); - this.pb = new GuiProgressBar( this.cvc, "guis/inscriber.png", 135, 39, 135, 177, 6, 18, Direction.VERTICAL ); + this.pb = new GuiProgressBar( this.cvc, "guis/inscriber.png", 135, 39, 135, 177, 6, 18, Direction.VERTICAL ); this.buttonList.add( this.pb ); } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/inscriber.png" ); - this.pb.xPosition = 135 + this.guiLeft; - this.pb.yPosition = 39 + this.guiTop; - - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - - if ( this.drawUpgrades() ) - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvc.availableUpgrades() * 18 ); - if ( this.hasToolbox() ) - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.pb.setFullMsg( this.cvc.getCurrentProgress() * 100 / this.cvc.getMaxProgress() + "%" ); @@ -75,14 +67,23 @@ public class GuiInscriber extends AEBaseGui this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/inscriber.png" ); + this.pb.xPosition = 135 + this.guiLeft; + this.pb.yPosition = 39 + this.guiTop; + + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); + + if( this.drawUpgrades() ) + this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvc.availableUpgrades() * 18 ); + if( this.hasToolbox() ) + this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 ); + } + protected boolean drawUpgrades() { return true; } - - protected boolean hasToolbox() - { - return ((ContainerUpgradeable) this.inventorySlots).hasToolbox(); - } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInterface.java b/src/main/java/appeng/client/gui/implementations/GuiInterface.java index 776508302..92b8b7d9b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterface.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterface.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import org.lwjgl.input.Mouse; import net.minecraft.client.gui.GuiButton; @@ -36,6 +37,7 @@ import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.helpers.IInterfaceHost; + public class GuiInterface extends GuiUpgradeable { @@ -43,30 +45,12 @@ public class GuiInterface extends GuiUpgradeable GuiImgButton BlockMode; GuiToggleButton interfaceMode; - public GuiInterface(InventoryPlayer inventoryPlayer, IInterfaceHost te) { + public GuiInterface( InventoryPlayer inventoryPlayer, IInterfaceHost te ) + { super( new ContainerInterface( inventoryPlayer, te ) ); this.ySize = 211; } - @Override - protected void actionPerformed(GuiButton btn) - { - super.actionPerformed( btn ); - - boolean backwards = Mouse.isButtonDown( 1 ); - - if ( btn == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - - if ( btn == this.interfaceMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( Settings.INTERFACE_TERMINAL, backwards ) ); - - if ( btn == this.BlockMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.BlockMode.getSetting(), backwards ) ); - } - @Override protected void addButtons() { @@ -76,25 +60,18 @@ public class GuiInterface extends GuiUpgradeable this.BlockMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO ); this.buttonList.add( this.BlockMode ); - this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal.getLocal(), - GuiText.InterfaceTerminalHint.getLocal() ); + this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal.getLocal(), GuiText.InterfaceTerminalHint.getLocal() ); this.buttonList.add( this.interfaceMode ); } @Override - protected String getBackground() + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - return "guis/interface.png"; - } + if( this.BlockMode != null ) + this.BlockMode.set( ( (ContainerInterface) this.cvb ).bMode ); - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - if ( this.BlockMode != null ) - this.BlockMode.set( ((ContainerInterface) this.cvb).bMode ); - - if ( this.interfaceMode != null ) - this.interfaceMode.setState( ((ContainerInterface) this.cvb).iTermMode == YesNo.YES ); + if( this.interfaceMode != null ) + this.interfaceMode.setState( ( (ContainerInterface) this.cvb ).iTermMode == YesNo.YES ); this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Interface.getLocal() ), 8, 6, 4210752 ); @@ -104,4 +81,29 @@ public class GuiInterface extends GuiUpgradeable this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); } + + @Override + protected String getBackground() + { + return "guis/interface.png"; + } + + @Override + protected void actionPerformed( GuiButton btn ) + { + super.actionPerformed( btn ); + + boolean backwards = Mouse.isButtonDown( 1 ); + + if( btn == this.priority ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); + } + + if( btn == this.interfaceMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( Settings.INTERFACE_TERMINAL, backwards ) ); + + if( btn == this.BlockMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.BlockMode.getSetting(), backwards ) ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java b/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java index 485d1489c..659cc71fd 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java @@ -28,8 +28,6 @@ import java.util.Map; import java.util.Set; import java.util.WeakHashMap; -import com.google.common.collect.HashMultimap; - import org.lwjgl.opengl.GL11; import net.minecraft.entity.player.InventoryPlayer; @@ -37,6 +35,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; +import com.google.common.collect.HashMultimap; + import appeng.api.AEApi; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiScrollbar; @@ -48,6 +48,7 @@ import appeng.core.localization.GuiText; import appeng.parts.reporting.PartMonitor; import appeng.util.Platform; + public class GuiInterfaceTerminal extends AEBaseGui { @@ -66,7 +67,7 @@ public class GuiInterfaceTerminal extends AEBaseGui private boolean refreshList = false; private MEGuiTextField searchField; - public GuiInterfaceTerminal(InventoryPlayer inventoryPlayer, PartMonitor te) + public GuiInterfaceTerminal( InventoryPlayer inventoryPlayer, PartMonitor te ) { super( new ContainerInterfaceTerminal( inventoryPlayer, te ) ); this.myScrollBar = new GuiScrollbar(); @@ -92,11 +93,54 @@ public class GuiInterfaceTerminal extends AEBaseGui } @Override - protected void mouseClicked(int xCoord, int yCoord, int btn) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.InterfaceTerminal.getLocal() ), 8, 6, 4210752 ); + this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + + int offset = 17; + int ex = this.myScrollBar.getCurrentScroll(); + + Iterator o = this.inventorySlots.inventorySlots.iterator(); + while( o.hasNext() ) + { + if( o.next() instanceof SlotDisconnected ) + o.remove(); + } + + for( int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++ ) + { + Object lineObj = this.lines.get( ex + x ); + if( lineObj instanceof ClientDCInternalInv ) + { + ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; + for( int z = 0; z < inv.inv.getSizeInventory(); z++ ) + { + this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z, z * 18 + 8, 1 + offset ) ); + } + } + else if( lineObj instanceof String ) + { + String name = (String) lineObj; + int rows = this.byName.get( name ).size(); + if( rows > 1 ) + name = name + " (" + rows + ')'; + + while( name.length() > 2 && this.fontRendererObj.getStringWidth( name ) > 155 ) + name = name.substring( 0, name.length() - 1 ); + + this.fontRendererObj.drawString( name, 10, 6 + offset, 4210752 ); + } + offset += 18; + } + } + + @Override + protected void mouseClicked( int xCoord, int yCoord, int btn ) { this.searchField.mouseClicked( xCoord, yCoord, btn ); - if ( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) + if( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) { this.searchField.setText( "" ); this.refreshList(); @@ -106,26 +150,7 @@ public class GuiInterfaceTerminal extends AEBaseGui } @Override - protected void keyTyped(char character, int key) - { - if ( !this.checkHotbarKeys( key ) ) - { - if ( character == ' ' && this.searchField.getText().length() == 0 ) - return; - - if ( this.searchField.textboxKeyTyped( character, key ) ) - { - this.refreshList(); - } - else - { - super.keyTyped( character, key ); - } - } - } - - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.bindTexture( "guis/interfaceterminal.png" ); this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); @@ -133,10 +158,10 @@ public class GuiInterfaceTerminal extends AEBaseGui int offset = 17; int ex = this.myScrollBar.getCurrentScroll(); - for (int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++) + for( int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++ ) { Object lineObj = this.lines.get( ex + x ); - if ( lineObj instanceof ClientDCInternalInv ) + if( lineObj instanceof ClientDCInternalInv ) { ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; @@ -147,65 +172,41 @@ public class GuiInterfaceTerminal extends AEBaseGui offset += 18; } - if ( this.searchField != null ) + if( this.searchField != null ) this.searchField.drawTextBox(); } @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + protected void keyTyped( char character, int key ) { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.InterfaceTerminal.getLocal() ), 8, 6, 4210752 ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - - int offset = 17; - int ex = this.myScrollBar.getCurrentScroll(); - - Iterator o = this.inventorySlots.inventorySlots.iterator(); - while (o.hasNext()) + if( !this.checkHotbarKeys( key ) ) { - if ( o.next() instanceof SlotDisconnected ) - o.remove(); - } + if( character == ' ' && this.searchField.getText().length() == 0 ) + return; - for (int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++) - { - Object lineObj = this.lines.get( ex + x ); - if ( lineObj instanceof ClientDCInternalInv ) + if( this.searchField.textboxKeyTyped( character, key ) ) { - ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; - for (int z = 0; z < inv.inv.getSizeInventory(); z++) - { - this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z, z * 18 + 8, 1 + offset ) ); - } + this.refreshList(); } - else if ( lineObj instanceof String ) + else { - String name = (String) lineObj; - int rows = this.byName.get( name ).size(); - if ( rows > 1 ) - name = name + " (" + rows + ')'; - - while (name.length() > 2 && this.fontRendererObj.getStringWidth( name ) > 155) - name = name.substring( 0, name.length() - 1 ); - - this.fontRendererObj.drawString( name, 10, 6 + offset, 4210752 ); + super.keyTyped( character, key ); } - offset += 18; } } - public void postUpdate(NBTTagCompound in) + public void postUpdate( NBTTagCompound in ) { - if ( in.getBoolean( "clear" ) ) + if( in.getBoolean( "clear" ) ) { this.byId.clear(); this.refreshList = true; } - for (Object oKey : in.func_150296_c()) + for( Object oKey : in.func_150296_c() ) { String key = (String) oKey; - if ( key.startsWith( "=" ) ) + if( key.startsWith( "=" ) ) { try { @@ -213,20 +214,20 @@ public class GuiInterfaceTerminal extends AEBaseGui NBTTagCompound invData = in.getCompoundTag( key ); ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) ); - for (int x = 0; x < current.inv.getSizeInventory(); x++) + for( int x = 0; x < current.inv.getSizeInventory(); x++ ) { String which = Integer.toString( x ); - if ( invData.hasKey( which ) ) + if( invData.hasKey( which ) ) current.inv.setInventorySlotContents( x, ItemStack.loadItemStackFromNBT( invData.getCompoundTag( which ) ) ); } } - catch (NumberFormatException ignored) + catch( NumberFormatException ignored ) { } } } - if ( this.refreshList ) + if( this.refreshList ) { this.refreshList = false; // invalid caches on refresh @@ -249,10 +250,10 @@ public class GuiInterfaceTerminal extends AEBaseGui final Set cachedSearch = this.getCacheForSearchTerm( searchFilterLowerCase ); final boolean rebuild = cachedSearch.isEmpty(); - for (ClientDCInternalInv entry : this.byId.values()) + for( ClientDCInternalInv entry : this.byId.values() ) { // ignore inventory if not doing a full rebuild or cache already marks it as miss. - if ( !rebuild && !cachedSearch.contains( entry ) ) + if( !rebuild && !cachedSearch.contains( entry ) ) { continue; } @@ -261,12 +262,12 @@ public class GuiInterfaceTerminal extends AEBaseGui boolean found = searchFilterLowerCase.isEmpty(); // Search if the current inventory holds a pattern containing the search term. - if ( !found && !searchFilterLowerCase.isEmpty() ) + if( !found && !searchFilterLowerCase.isEmpty() ) { - for (ItemStack itemStack : entry.inv) + for( ItemStack itemStack : entry.inv ) { found = this.itemStackMatchesSearchTerm( itemStack, searchFilterLowerCase ); - if ( found ) + if( found ) { break; } @@ -274,7 +275,7 @@ public class GuiInterfaceTerminal extends AEBaseGui } // if found, filter skipped or machine name matching the search term, add it - if ( found || entry.getName().toLowerCase().contains( searchFilterLowerCase ) ) + if( found || entry.getName().toLowerCase().contains( searchFilterLowerCase ) ) { this.byName.put( entry.getName(), entry ); cachedSearch.add( entry ); @@ -293,7 +294,7 @@ public class GuiInterfaceTerminal extends AEBaseGui this.lines.clear(); this.lines.ensureCapacity( this.getMaxRows() ); - for (String n : this.names) + for( String n : this.names ) { this.lines.add( n ); @@ -307,16 +308,16 @@ public class GuiInterfaceTerminal extends AEBaseGui this.myScrollBar.setRange( 0, this.lines.size() - LINES_ON_PAGE, 2 ); } - private boolean itemStackMatchesSearchTerm(ItemStack itemStack, String searchTerm) + private boolean itemStackMatchesSearchTerm( ItemStack itemStack, String searchTerm ) { - if ( itemStack == null ) + if( itemStack == null ) { return false; } NBTTagCompound encodedValue = itemStack.getTagCompound(); - if ( encodedValue == null ) + if( encodedValue == null ) { return false; } @@ -325,19 +326,18 @@ public class GuiInterfaceTerminal extends AEBaseGui // NBTTagList inTag = encodedValue.getTagList( "in", 10 ); NBTTagList outTag = encodedValue.getTagList( "out", 10 ); - for (int i = 0; i < outTag.tagCount(); i++) + for( int i = 0; i < outTag.tagCount(); i++ ) { ItemStack parsedItemStack = ItemStack.loadItemStackFromNBT( outTag.getCompoundTagAt( i ) ); - if ( parsedItemStack != null ) + if( parsedItemStack != null ) { String displayName = Platform.getItemDisplayName( AEApi.instance().storage().createItemStack( parsedItemStack ) ).toLowerCase(); - if ( displayName.contains( searchTerm ) ) + if( displayName.contains( searchTerm ) ) { return true; } } - } return false; } @@ -348,20 +348,20 @@ public class GuiInterfaceTerminal extends AEBaseGui * If this cache should be empty, it will populate it with an earlier cache if available or at least the cache for * the empty string. * - * @param searchTerm - * the corresponding search + * @param searchTerm the corresponding search + * * @return a Set matching a superset of the search term */ - private Set getCacheForSearchTerm(String searchTerm) + private Set getCacheForSearchTerm( String searchTerm ) { - if ( !this.cachedSearches.containsKey( searchTerm ) ) + if( !this.cachedSearches.containsKey( searchTerm ) ) { this.cachedSearches.put( searchTerm, new HashSet() ); } Set cache = this.cachedSearches.get( searchTerm ); - if ( cache.isEmpty() && searchTerm.length() > 1 ) + if( cache.isEmpty() && searchTerm.length() > 1 ) { cache.addAll( this.getCacheForSearchTerm( searchTerm.substring( 0, searchTerm.length() - 1 ) ) ); return cache; @@ -380,11 +380,11 @@ public class GuiInterfaceTerminal extends AEBaseGui return this.names.size() + this.byId.size(); } - private ClientDCInternalInv getById(long id, long sortBy, String string) + private ClientDCInternalInv getById( long id, long sortBy, String string ) { ClientDCInternalInv o = this.byId.get( id ); - if ( o == null ) + if( o == null ) { this.byId.put( id, o = new ClientDCInternalInv( 9, id, sortBy, string ) ); this.refreshList = true; diff --git a/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java b/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java index 597297919..faa6c887c 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java +++ b/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import java.io.IOException; import org.lwjgl.input.Mouse; @@ -42,6 +43,7 @@ import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketValueConfig; import appeng.parts.automation.PartLevelEmitter; + public class GuiLevelEmitter extends GuiUpgradeable { @@ -59,7 +61,8 @@ public class GuiLevelEmitter extends GuiUpgradeable GuiImgButton levelMode; GuiImgButton craftingMode; - public GuiLevelEmitter(InventoryPlayer inventoryPlayer, PartLevelEmitter te) { + public GuiLevelEmitter( InventoryPlayer inventoryPlayer, PartLevelEmitter te ) + { super( new ContainerLevelEmitter( inventoryPlayer, te ) ); } @@ -74,7 +77,7 @@ public class GuiLevelEmitter extends GuiUpgradeable this.level.setTextColor( 0xFFFFFF ); this.level.setVisible( true ); this.level.setFocused( true ); - ((ContainerLevelEmitter) this.inventorySlots).setTextField( this.level ); + ( (ContainerLevelEmitter) this.inventorySlots ).setTextField( this.level ); } @Override @@ -107,111 +110,7 @@ public class GuiLevelEmitter extends GuiUpgradeable } @Override - protected void actionPerformed(GuiButton btn) - { - super.actionPerformed( btn ); - - boolean backwards = Mouse.isButtonDown( 1 ); - - if ( btn == this.craftingMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.craftingMode.getSetting(), backwards ) ); - - if ( btn == this.levelMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.levelMode.getSetting(), backwards ) ); - - boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - - if ( isPlus || isMinus ) - this.addQty( this.getQty( btn ) ); - } - - private void addQty(long i) - { - try - { - String Out = this.level.getText(); - - boolean Fixed = false; - while (Out.startsWith( "0" ) && Out.length() > 1) - { - Out = Out.substring( 1 ); - Fixed = true; - } - - if ( Fixed ) - this.level.setText( Out ); - - if ( Out.length() == 0 ) - Out = "0"; - - long result = Long.parseLong( Out ); - result += i; - if ( result < 0 ) - result = 0; - - this.level.setText( Out = Long.toString( result ) ); - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); - } - catch (NumberFormatException e) - { - // nope.. - this.level.setText( "0" ); - } - catch (IOException e) - { - AELog.error( e ); - } - } - - @Override - protected void handleButtonVisibility() - { - this.craftingMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ); - this.fuzzyMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ); - } - - @Override - protected void keyTyped(char character, int key) - { - if ( !this.checkHotbarKeys( key ) ) - { - if ( (key == 211 || key == 205 || key == 203 || key == 14 || Character.isDigit( character )) && this.level.textboxKeyTyped( character, key ) ) - { - try - { - String Out = this.level.getText(); - - boolean Fixed = false; - while (Out.startsWith( "0" ) && Out.length() > 1) - { - Out = Out.substring( 1 ); - Fixed = true; - } - - if ( Fixed ) - this.level.setText( Out ); - - if ( Out.length() == 0 ) - Out = "0"; - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); - } - catch (IOException e) - { - AELog.error( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { boolean notCraftingMode = this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) == 0; @@ -230,20 +129,27 @@ public class GuiLevelEmitter extends GuiUpgradeable super.drawFG( offsetX, offsetY, mouseX, mouseY ); - if ( this.craftingMode != null ) - this.craftingMode.set( ((ContainerLevelEmitter) this.cvb).cmType ); + if( this.craftingMode != null ) + this.craftingMode.set( ( (ContainerLevelEmitter) this.cvb ).cmType ); - if ( this.levelMode != null ) - this.levelMode.set( ((ContainerLevelEmitter) this.cvb).lvType ); + if( this.levelMode != null ) + this.levelMode.set( ( (ContainerLevelEmitter) this.cvb ).lvType ); } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) { super.drawBG( offsetX, offsetY, mouseX, mouseY ); this.level.drawTextBox(); } + @Override + protected void handleButtonVisibility() + { + this.craftingMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ); + this.fuzzyMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ); + } + @Override protected String getBackground() { @@ -255,4 +161,101 @@ public class GuiLevelEmitter extends GuiUpgradeable { return GuiText.LevelEmitter; } + + @Override + protected void actionPerformed( GuiButton btn ) + { + super.actionPerformed( btn ); + + boolean backwards = Mouse.isButtonDown( 1 ); + + if( btn == this.craftingMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.craftingMode.getSetting(), backwards ) ); + + if( btn == this.levelMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.levelMode.getSetting(), backwards ) ); + + boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + + if( isPlus || isMinus ) + this.addQty( this.getQty( btn ) ); + } + + private void addQty( long i ) + { + try + { + String Out = this.level.getText(); + + boolean Fixed = false; + while( Out.startsWith( "0" ) && Out.length() > 1 ) + { + Out = Out.substring( 1 ); + Fixed = true; + } + + if( Fixed ) + this.level.setText( Out ); + + if( Out.length() == 0 ) + Out = "0"; + + long result = Long.parseLong( Out ); + result += i; + if( result < 0 ) + result = 0; + + this.level.setText( Out = Long.toString( result ) ); + + NetworkHandler.instance.sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); + } + catch( NumberFormatException e ) + { + // nope.. + this.level.setText( "0" ); + } + catch( IOException e ) + { + AELog.error( e ); + } + } + + @Override + protected void keyTyped( char character, int key ) + { + if( !this.checkHotbarKeys( key ) ) + { + if( ( key == 211 || key == 205 || key == 203 || key == 14 || Character.isDigit( character ) ) && this.level.textboxKeyTyped( character, key ) ) + { + try + { + String Out = this.level.getText(); + + boolean Fixed = false; + while( Out.startsWith( "0" ) && Out.length() > 1 ) + { + Out = Out.substring( 1 ); + Fixed = true; + } + + if( Fixed ) + this.level.setText( Out ); + + if( Out.length() == 0 ) + Out = "0"; + + NetworkHandler.instance.sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); + } + catch( IOException e ) + { + AELog.error( e ); + } + } + else + { + super.keyTyped( character, key ); + } + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMAC.java b/src/main/java/appeng/client/gui/implementations/GuiMAC.java index 265060e11..ef2598791 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMAC.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMAC.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.api.config.RedstoneMode; @@ -29,12 +30,20 @@ import appeng.container.implementations.ContainerMAC; import appeng.core.localization.GuiText; import appeng.tile.crafting.TileMolecularAssembler; + public class GuiMAC extends GuiUpgradeable { final ContainerMAC container; GuiProgressBar pb; + public GuiMAC( InventoryPlayer inventoryPlayer, TileMolecularAssembler te ) + { + super( new ContainerMAC( inventoryPlayer, te ) ); + this.ySize = 197; + this.container = (ContainerMAC) this.inventorySlots; + } + @Override public void initGui() { @@ -45,25 +54,25 @@ public class GuiMAC extends GuiUpgradeable } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) + protected void addButtons() { - this.pb.xPosition = 148 + this.guiLeft; - this.pb.yPosition = 48 + this.guiTop; - super.drawBG( offsetX, offsetY, mouseX, mouseY ); + this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); + this.buttonList.add( this.redstoneMode ); } @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.pb.setFullMsg( this.container.getCurrentProgress() + "%" ); super.drawFG( offsetX, offsetY, mouseX, mouseY ); } @Override - protected void addButtons() + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.buttonList.add( this.redstoneMode ); + this.pb.xPosition = 148 + this.guiLeft; + this.pb.yPosition = 48 + this.guiTop; + super.drawBG( offsetX, offsetY, mouseX, mouseY ); } @Override @@ -72,13 +81,6 @@ public class GuiMAC extends GuiUpgradeable return "guis/mac.png"; } - public GuiMAC(InventoryPlayer inventoryPlayer, TileMolecularAssembler te) - { - super( new ContainerMAC( inventoryPlayer, te ) ); - this.ySize = 197; - this.container = (ContainerMAC) this.inventorySlots; - } - @Override protected GuiText getName() { diff --git a/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java b/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java index b6037b101..5f5753128 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import java.io.IOException; import java.util.List; @@ -65,50 +66,42 @@ import appeng.tile.misc.TileSecurity; import appeng.util.IConfigManagerHost; import appeng.util.Platform; + public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfigManagerHost { - GuiTabButton craftingStatusBtn; - - MEGuiTextField searchField; - private static String memoryText = ""; - public static int CraftingGridOffsetX; public static int CraftingGridOffsetY; - + private static String memoryText = ""; final ItemRepo repo; - - GuiText myName; - final int offsetX = 9; + final int lowerTextureOffset = 0; + final IConfigManager configSrc; + final boolean viewCell; + final ItemStack[] myCurrentViewCells = new ItemStack[5]; + final ContainerMEMonitorable monitorableContainer; + GuiTabButton craftingStatusBtn; + MEGuiTextField searchField; + GuiText myName; int perRow = 9; int reservedSpace = 0; - final int lowerTextureOffset = 0; boolean customSortOrder = true; - int rows = 0; int maxRows = Integer.MAX_VALUE; - int standardSize; - - final IConfigManager configSrc; - GuiImgButton ViewBox; GuiImgButton SortByBox; GuiImgButton SortDirBox; - GuiImgButton searchBoxSettings; GuiImgButton terminalStyleBox; - final boolean viewCell; - final ItemStack[] myCurrentViewCells = new ItemStack[5]; - final ContainerMEMonitorable monitorableContainer; - - public GuiMEMonitorable(InventoryPlayer inventoryPlayer, ITerminalHost te) { + public GuiMEMonitorable( InventoryPlayer inventoryPlayer, ITerminalHost te ) + { this( inventoryPlayer, te, new ContainerMEMonitorable( inventoryPlayer, te ) ); } - public GuiMEMonitorable(InventoryPlayer inventoryPlayer, ITerminalHost te, ContainerMEMonitorable c) { + public GuiMEMonitorable( InventoryPlayer inventoryPlayer, ITerminalHost te, ContainerMEMonitorable c ) + { super( c ); this.myScrollBar = new GuiScrollbar(); @@ -117,31 +110,31 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi this.xSize = 185; this.ySize = 204; - if ( te instanceof IViewCellStorage ) + if( te instanceof IViewCellStorage ) this.xSize += 33; this.standardSize = this.xSize; - this.configSrc = ((IConfigurableObject) this.inventorySlots).getConfigManager(); - (this.monitorableContainer = (ContainerMEMonitorable) this.inventorySlots).gui = this; + this.configSrc = ( (IConfigurableObject) this.inventorySlots ).getConfigManager(); + ( this.monitorableContainer = (ContainerMEMonitorable) this.inventorySlots ).gui = this; this.viewCell = te instanceof IViewCellStorage; - if ( te instanceof TileSecurity ) + if( te instanceof TileSecurity ) this.myName = GuiText.Security; - else if ( te instanceof WirelessTerminalGuiObject ) + else if( te instanceof WirelessTerminalGuiObject ) this.myName = GuiText.WirelessTerminal; - else if ( te instanceof IPortableCell ) + else if( te instanceof IPortableCell ) this.myName = GuiText.PortableCell; - else if ( te instanceof IMEChest ) + else if( te instanceof IMEChest ) this.myName = GuiText.Chest; - else if ( te instanceof PartTerminal ) + else if( te instanceof PartTerminal ) this.myName = GuiText.Terminal; } - public void postUpdate(List list) + public void postUpdate( List list ) { - for (IAEItemStack is : list) + for( IAEItemStack is : list ) this.repo.postUpdate( is ); this.repo.updateView(); @@ -151,7 +144,49 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi private void setScrollBar() { this.myScrollBar.setTop( 18 ).setLeft( 175 ).setHeight( this.rows * 18 - 2 ); - this.myScrollBar.setRange( 0, (this.repo.size() + this.perRow - 1) / this.perRow - this.rows, Math.max( 1, this.rows / 6 ) ); + this.myScrollBar.setRange( 0, ( this.repo.size() + this.perRow - 1 ) / this.perRow - this.rows, Math.max( 1, this.rows / 6 ) ); + } + + @Override + protected void actionPerformed( GuiButton btn ) + { + if( btn == this.craftingStatusBtn ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_CRAFTING_STATUS ) ); + } + + if( btn instanceof GuiImgButton ) + { + boolean backwards = Mouse.isButtonDown( 1 ); + + GuiImgButton iBtn = (GuiImgButton) btn; + if( iBtn.getSetting() != Settings.ACTIONS ) + { + Enum cv = iBtn.getCurrentValue(); + Enum next = Platform.rotateEnum( cv, backwards, iBtn.getSetting().getPossibleValues() ); + + if( btn == this.terminalStyleBox ) + AEConfig.instance.settings.putSetting( iBtn.getSetting(), next ); + else if( btn == this.searchBoxSettings ) + AEConfig.instance.settings.putSetting( iBtn.getSetting(), next ); + else + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( iBtn.getSetting().name(), next.name() ) ); + } + catch( IOException e ) + { + AELog.error( e ); + } + } + + iBtn.set( next ); + + if( next.getClass() == SearchBoxMode.class || next.getClass() == TerminalStyle.class ) + this.re_init(); + } + } } public void re_init() @@ -160,18 +195,11 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi this.initGui(); } - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - memoryText = this.searchField.getText(); - } - @Override public void initGui() { this.maxRows = this.getMaxRows(); - this.perRow = AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ? 9 : 9 + ((this.width - this.standardSize) / 18); + this.perRow = AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ? 9 : 9 + ( ( this.width - this.standardSize ) / 18 ); boolean hasNEI = AppEng.instance.isIntegrationEnabled( IntegrationType.NEI ); @@ -182,29 +210,29 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi int extraSpace = this.height - magicNumber - NEI - top - this.reservedSpace; this.rows = (int) Math.floor( extraSpace / 18 ); - if ( this.rows > this.maxRows ) + if( this.rows > this.maxRows ) { - top += (this.rows - this.maxRows) * 18 / 2; + top += ( this.rows - this.maxRows ) * 18 / 2; this.rows = this.maxRows; } - if ( hasNEI ) + if( hasNEI ) this.rows--; - if ( this.rows < 3 ) + if( this.rows < 3 ) this.rows = 3; this.meSlots.clear(); - for (int y = 0; y < this.rows; y++) + for( int y = 0; y < this.rows; y++ ) { - for (int x = 0; x < this.perRow; x++) + for( int x = 0; x < this.perRow; x++ ) { this.meSlots.add( new InternalSlotME( this.repo, x + y * this.perRow, this.offsetX + x * 18, 18 + y * 18 ) ); } } - if ( AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ) - this.xSize = this.standardSize + ((this.perRow - 9) * 18); + if( AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ) + this.xSize = this.standardSize + ( ( this.perRow - 9 ) * 18 ); else this.xSize = this.standardSize; @@ -216,17 +244,17 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi this.ySize = magicNumber + this.rows * 18 + this.reservedSpace; // this.guiTop = top; int unusedSpace = this.height - this.ySize; - this.guiTop = (int) Math.floor( unusedSpace / (unusedSpace < 0 ? 3.8f : 2.0f) ); + this.guiTop = (int) Math.floor( unusedSpace / ( unusedSpace < 0 ? 3.8f : 2.0f ) ); int offset = this.guiTop + 8; - if ( this.customSortOrder ) + if( this.customSortOrder ) { this.buttonList.add( this.SortByBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_BY, this.configSrc.getSetting( Settings.SORT_BY ) ) ); offset += 20; } - if ( this.viewCell || this instanceof GuiWirelessTerm ) + if( this.viewCell || this instanceof GuiWirelessTerm ) { this.buttonList.add( this.ViewBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.VIEW_MODE, this.configSrc.getSetting( Settings.VIEW_MODE ) ) ); offset += 20; @@ -235,14 +263,12 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi this.buttonList.add( this.SortDirBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_DIRECTION, this.configSrc.getSetting( Settings.SORT_DIRECTION ) ) ); offset += 20; - this.buttonList.add( this.searchBoxSettings = new GuiImgButton( this.guiLeft - 18, offset, Settings.SEARCH_MODE, AEConfig.instance.settings - .getSetting( Settings.SEARCH_MODE ) ) ); + this.buttonList.add( this.searchBoxSettings = new GuiImgButton( this.guiLeft - 18, offset, Settings.SEARCH_MODE, AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ) ) ); offset += 20; - if ( !(this instanceof GuiMEPortableCell) || this instanceof GuiWirelessTerm ) + if( !( this instanceof GuiMEPortableCell ) || this instanceof GuiWirelessTerm ) { - this.buttonList.add( this.terminalStyleBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.TERMINAL_STYLE, AEConfig.instance.settings - .getSetting( Settings.TERMINAL_STYLE ) ) ); + this.buttonList.add( this.terminalStyleBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.TERMINAL_STYLE, AEConfig.instance.settings.getSetting( Settings.TERMINAL_STYLE ) ) ); } this.searchField = new MEGuiTextField( this.fontRendererObj, this.guiLeft + Math.max( 80, this.offsetX ), this.guiTop + 4, 90, 12 ); @@ -251,10 +277,9 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi this.searchField.setTextColor( 0xFFFFFF ); this.searchField.setVisible( true ); - if ( this.viewCell || this instanceof GuiWirelessTerm ) + if( this.viewCell || this instanceof GuiWirelessTerm ) { - this.buttonList.add( this.craftingStatusBtn = new GuiTabButton( this.guiLeft + 170, this.guiTop - 4, 2 + 11 * 16, GuiText.CraftingStatus.getLocal(), - itemRender ) ); + this.buttonList.add( this.craftingStatusBtn = new GuiTabButton( this.guiLeft + 170, this.guiTop - 4, 2 + 11 * 16, GuiText.CraftingStatus.getLocal(), itemRender ) ); this.craftingStatusBtn.hideEdge = 13; } @@ -262,7 +287,7 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi Enum setting = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); this.searchField.setFocused( SearchBoxMode.AUTOSEARCH == setting || SearchBoxMode.NEI_AUTOSEARCH == setting ); - if ( this.isSubGui() ) + if( this.isSubGui() ) { this.searchField.setText( memoryText ); this.repo.searchString = memoryText; @@ -273,18 +298,18 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi CraftingGridOffsetX = Integer.MAX_VALUE; CraftingGridOffsetY = Integer.MAX_VALUE; - for (Object s : this.inventorySlots.inventorySlots) + for( Object s : this.inventorySlots.inventorySlots ) { - if ( s instanceof AppEngSlot ) + if( s instanceof AppEngSlot ) { - if ( ((AppEngSlot) s).xDisplayPosition < 197 ) + if( ( (AppEngSlot) s ).xDisplayPosition < 197 ) this.repositionSlot( (AppEngSlot) s ); } - if ( s instanceof SlotCraftingMatrix || s instanceof SlotFakeCraftingMatrix ) + if( s instanceof SlotCraftingMatrix || s instanceof SlotFakeCraftingMatrix ) { Slot g = (Slot) s; - if ( g.xDisplayPosition > 0 && g.yDisplayPosition > 0 ) + if( g.xDisplayPosition > 0 && g.yDisplayPosition > 0 ) { CraftingGridOffsetX = Math.min( CraftingGridOffsetX, g.xDisplayPosition ); CraftingGridOffsetY = Math.min( CraftingGridOffsetY, g.yDisplayPosition ); @@ -296,64 +321,24 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi CraftingGridOffsetY -= 6; } - protected void repositionSlot(AppEngSlot s) + @Override + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - s.yDisplayPosition = s.defY + this.ySize - 78 - 5; + this.fontRendererObj.drawString( this.getGuiDisplayName( this.myName.getLocal() ), 8, 6, 4210752 ); + this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); } @Override - protected void actionPerformed(GuiButton btn) - { - if ( btn == this.craftingStatusBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_CRAFTING_STATUS ) ); - } - - if ( btn instanceof GuiImgButton ) - { - boolean backwards = Mouse.isButtonDown( 1 ); - - GuiImgButton iBtn = (GuiImgButton) btn; - if ( iBtn.getSetting() != Settings.ACTIONS ) - { - Enum cv = iBtn.getCurrentValue(); - Enum next = Platform.rotateEnum( cv, backwards, iBtn.getSetting().getPossibleValues() ); - - if ( btn == this.terminalStyleBox ) - AEConfig.instance.settings.putSetting( iBtn.getSetting(), next ); - else if ( btn == this.searchBoxSettings ) - AEConfig.instance.settings.putSetting( iBtn.getSetting(), next ); - else - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( iBtn.getSetting().name(), next.name() ) ); - } - catch (IOException e) - { - AELog.error( e ); - } - } - - iBtn.set( next ); - - if ( next.getClass() == SearchBoxMode.class || next.getClass() == TerminalStyle.class ) - this.re_init(); - } - } - } - - @Override - protected void mouseClicked(int xCoord, int yCoord, int btn) + protected void mouseClicked( int xCoord, int yCoord, int btn ) { Enum searchMode = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - if ( searchMode != SearchBoxMode.AUTOSEARCH && searchMode != SearchBoxMode.NEI_AUTOSEARCH ) + if( searchMode != SearchBoxMode.AUTOSEARCH && searchMode != SearchBoxMode.NEI_AUTOSEARCH ) { this.searchField.mouseClicked( xCoord, yCoord, btn ); } - if ( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) + if( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) { this.searchField.setText( "" ); this.repo.searchString = ""; @@ -365,14 +350,79 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi } @Override - protected void keyTyped(char character, int key) + public void onGuiClosed() { - if ( !this.checkHotbarKeys( key ) ) + super.onGuiClosed(); + memoryText = this.searchField.getText(); + } + + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + int x_width = 197; + + this.bindTexture( this.getBackground() ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, x_width, 18 ); + + if( this.viewCell || ( this instanceof GuiSecurity ) ) + this.drawTexturedModalRect( offsetX + x_width, offsetY, x_width, 0, 46, 128 ); + + for( int x = 0; x < this.rows; x++ ) + this.drawTexturedModalRect( offsetX, offsetY + 18 + x * 18, 0, 18, x_width, 18 ); + + this.drawTexturedModalRect( offsetX, offsetY + 16 + this.rows * 18 + this.lowerTextureOffset, 0, 106 - 18 - 18, x_width, 99 + this.reservedSpace - this.lowerTextureOffset ); + + if( this.viewCell ) { - if ( character == ' ' && this.searchField.getText().length() == 0 ) + boolean update = false; + + for( int i = 0; i < 5; i++ ) + { + if( this.myCurrentViewCells[i] != this.monitorableContainer.cellView[i].getStack() ) + { + update = true; + this.myCurrentViewCells[i] = this.monitorableContainer.cellView[i].getStack(); + } + } + + if( update ) + this.repo.setViewCell( this.myCurrentViewCells ); + } + + if( this.searchField != null ) + this.searchField.drawTextBox(); + } + + protected String getBackground() + { + return "guis/terminal.png"; + } + + @Override + protected boolean isPowered() + { + return this.repo.hasPower(); + } + + int getMaxRows() + { + return AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) == TerminalStyle.SMALL ? 6 : Integer.MAX_VALUE; + } + + protected void repositionSlot( AppEngSlot s ) + { + s.yDisplayPosition = s.defY + this.ySize - 78 - 5; + } + + @Override + protected void keyTyped( char character, int key ) + { + if( !this.checkHotbarKeys( key ) ) + { + if( character == ' ' && this.searchField.getText().length() == 0 ) return; - if ( this.searchField.textboxKeyTyped( character, key ) ) + if( this.searchField.textboxKeyTyped( character, key ) ) { this.repo.searchString = this.searchField.getText(); this.repo.updateView(); @@ -392,55 +442,6 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi super.updateScreen(); } - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - int x_width = 197; - - this.bindTexture( this.getBackground() ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, x_width, 18 ); - - if ( this.viewCell || (this instanceof GuiSecurity) ) - this.drawTexturedModalRect( offsetX + x_width, offsetY, x_width, 0, 46, 128 ); - - for (int x = 0; x < this.rows; x++) - this.drawTexturedModalRect( offsetX, offsetY + 18 + x * 18, 0, 18, x_width, 18 ); - - this.drawTexturedModalRect( offsetX, offsetY + 16 + this.rows * 18 + this.lowerTextureOffset, 0, 106 - 18 - 18, x_width, 99 + this.reservedSpace - this.lowerTextureOffset ); - - if ( this.viewCell ) - { - boolean update = false; - - for (int i = 0; i < 5; i++) - { - if ( this.myCurrentViewCells[i] != this.monitorableContainer.cellView[i].getStack() ) - { - update = true; - this.myCurrentViewCells[i] = this.monitorableContainer.cellView[i].getStack(); - } - } - - if ( update ) - this.repo.setViewCell( this.myCurrentViewCells ); - } - - if ( this.searchField != null ) - this.searchField.drawTextBox(); - } - - protected String getBackground() - { - return "guis/terminal.png"; - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( this.myName.getLocal() ), 8, 6, 4210752 ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } - @Override public Enum getSortBy() { @@ -460,29 +461,17 @@ public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfi } @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { - if ( this.SortByBox != null ) + if( this.SortByBox != null ) this.SortByBox.set( this.configSrc.getSetting( Settings.SORT_BY ) ); - if ( this.SortDirBox != null ) + if( this.SortDirBox != null ) this.SortDirBox.set( this.configSrc.getSetting( Settings.SORT_DIRECTION ) ); - if ( this.ViewBox != null ) + if( this.ViewBox != null ) this.ViewBox.set( this.configSrc.getSetting( Settings.VIEW_MODE ) ); this.repo.updateView(); } - - @Override - protected boolean isPowered() - { - return this.repo.hasPower(); - } - - int getMaxRows() - { - return AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) == TerminalStyle.SMALL ? 6 : Integer.MAX_VALUE; - } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java b/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java index 92b463fe7..85c1fb870 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java @@ -18,15 +18,18 @@ package appeng.client.gui.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.api.implementations.guiobjects.IPortableCell; import appeng.container.implementations.ContainerMEPortableCell; + public class GuiMEPortableCell extends GuiMEMonitorable { - public GuiMEPortableCell(InventoryPlayer inventoryPlayer, IPortableCell te) { + public GuiMEPortableCell( InventoryPlayer inventoryPlayer, IPortableCell te ) + { super( inventoryPlayer, te, new ContainerMEPortableCell( inventoryPlayer, null ) ); } diff --git a/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java b/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java index e5ea970f0..c69c4a647 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java @@ -46,15 +46,17 @@ import appeng.core.AEConfig; import appeng.core.localization.GuiText; import appeng.util.Platform; + public class GuiNetworkStatus extends AEBaseGui implements ISortSource { final ItemRepo repo; - GuiImgButton units; - final int rows = 4; + GuiImgButton units; + int tooltip = -1; - public GuiNetworkStatus(InventoryPlayer inventoryPlayer, INetworkTool te) { + public GuiNetworkStatus( InventoryPlayer inventoryPlayer, INetworkTool te ) + { super( new ContainerNetworkStatus( inventoryPlayer, te ) ); this.ySize = 153; this.xSize = 195; @@ -64,13 +66,13 @@ public class GuiNetworkStatus extends AEBaseGui implements ISortSource } @Override - protected void actionPerformed(GuiButton btn) + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); boolean backwards = Mouse.isButtonDown( 1 ); - if ( btn == this.units ) + if( btn == this.units ) { AEConfig.instance.nextPowerUnit( backwards ); this.units.set( AEConfig.instance.selectedPowerUnit() ); @@ -86,62 +88,34 @@ public class GuiNetworkStatus extends AEBaseGui implements ISortSource this.buttonList.add( this.units ); } - public void postUpdate(List list) - { - this.repo.clear(); - - for (IAEItemStack is : list) - this.repo.postUpdate( is ); - - this.repo.updateView(); - this.setScrollBar(); - } - - private void setScrollBar() - { - int size = this.repo.size(); - this.myScrollBar.setTop( 39 ).setLeft( 175 ).setHeight( 78 ); - this.myScrollBar.setRange( 0, (size + 4) / 5 - this.rows, 1 ); - } - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/networkstatus.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - int tooltip = -1; - - @Override - public void drawScreen(int mouse_x, int mouse_y, float btn) + public void drawScreen( int mouse_x, int mouse_y, float btn ) { int x = 0; int y = 0; - int gx = (this.width - this.xSize) / 2; - int gy = (this.height - this.ySize) / 2; + int gx = ( this.width - this.xSize ) / 2; + int gy = ( this.height - this.ySize ) / 2; this.tooltip = -1; - for (int z = 0; z <= 4 * 5; z++) + for( int z = 0; z <= 4 * 5; z++ ) { int minX = gx + 14 + x * 31; int minY = gy + 41 + y * 18; - if ( minX < mouse_x && minX + 28 > mouse_x ) + if( minX < mouse_x && minX + 28 > mouse_x ) { - if ( minY < mouse_y && minY + 20 > mouse_y ) + if( minY < mouse_y && minY + 20 > mouse_y ) { this.tooltip = z; break; } - } x++; - if ( x > 4 ) + if( x > 4 ) { y++; x = 0; @@ -152,7 +126,7 @@ public class GuiNetworkStatus extends AEBaseGui implements ISortSource } @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { ContainerNetworkStatus ns = (ContainerNetworkStatus) this.inventorySlots; @@ -177,32 +151,31 @@ public class GuiNetworkStatus extends AEBaseGui implements ISortSource int toolPosX = 0; int toolPosY = 0; - for (int z = viewStart; z < Math.min( viewEnd, this.repo.size() ); z++) + for( int z = viewStart; z < Math.min( viewEnd, this.repo.size() ); z++ ) { IAEItemStack refStack = this.repo.getReferenceItem( z ); - if ( refStack != null ) + if( refStack != null ) { GL11.glPushMatrix(); GL11.glScaled( 0.5, 0.5, 0.5 ); String str = Long.toString( refStack.getStackSize() ); - if ( refStack.getStackSize() >= 10000 ) + if( refStack.getStackSize() >= 10000 ) str = Long.toString( refStack.getStackSize() / 1000 ) + 'k'; int w = this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ((x * sectionLength + xo + sectionLength - 19 - (w * 0.5)) * 2), (y * 18 + yo + 6) * 2, - 4210752 ); + this.fontRendererObj.drawString( str, (int) ( ( x * sectionLength + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * 18 + yo + 6 ) * 2, 4210752 ); GL11.glPopMatrix(); int posX = x * sectionLength + xo + sectionLength - 18; int posY = y * 18 + yo; - if ( this.tooltip == z - viewStart ) + if( this.tooltip == z - viewStart ) { toolTip = Platform.getItemDisplayName( this.repo.getItem( z ) ); toolTip += ( '\n' + GuiText.Installed.getLocal() + ": " + ( refStack.getStackSize() ) ); - if ( refStack.getCountRequestable() > 0 ) + if( refStack.getCountRequestable() > 0 ) toolTip += ( '\n' + GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong( refStack.getCountRequestable(), true ) ); toolPosX = x * sectionLength + xo + sectionLength - 8; @@ -213,31 +186,54 @@ public class GuiNetworkStatus extends AEBaseGui implements ISortSource x++; - if ( x > 4 ) + if( x > 4 ) { y++; x = 0; } } - } - if ( this.tooltip >= 0 && toolTip.length() > 0 ) + if( this.tooltip >= 0 && toolTip.length() > 0 ) { GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); this.drawTooltip( toolPosX, toolPosY + 10, 0, toolTip ); GL11.glPopAttrib(); } + } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/networkstatus.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } + + public void postUpdate( List list ) + { + this.repo.clear(); + + for( IAEItemStack is : list ) + this.repo.postUpdate( is ); + + this.repo.updateView(); + this.setScrollBar(); + } + + private void setScrollBar() + { + int size = this.repo.size(); + this.myScrollBar.setTop( 39 ).setLeft( 175 ).setHeight( 78 ); + this.myScrollBar.setRange( 0, ( size + 4 ) / 5 - this.rows, 1 ); } // @Override - NEI - public List handleItemTooltip(ItemStack stack, int mouseX, int mouseY, List currentToolTip) + public List handleItemTooltip( ItemStack stack, int mouseX, int mouseY, List currentToolTip ) { - if ( stack != null ) + if( stack != null ) { Slot s = this.getSlot( mouseX, mouseY ); - if ( s instanceof SlotME ) + if( s instanceof SlotME ) { IAEItemStack myStack = null; @@ -246,15 +242,14 @@ public class GuiNetworkStatus extends AEBaseGui implements ISortSource SlotME theSlotField = (SlotME) s; myStack = theSlotField.getAEStack(); } - catch (Throwable ignore) + catch( Throwable ignore ) { } - if ( myStack != null ) + if( myStack != null ) { - while (currentToolTip.size() > 1) + while( currentToolTip.size() > 1 ) currentToolTip.remove( 1 ); - } } } @@ -262,10 +257,10 @@ public class GuiNetworkStatus extends AEBaseGui implements ISortSource } // Vanilla version... - protected void drawItemStackTooltip(ItemStack stack, int x, int y) + protected void drawItemStackTooltip( ItemStack stack, int x, int y ) { Slot s = this.getSlot( x, y ); - if ( s instanceof SlotME && stack != null ) + if( s instanceof SlotME && stack != null ) { IAEItemStack myStack = null; @@ -274,18 +269,18 @@ public class GuiNetworkStatus extends AEBaseGui implements ISortSource SlotME theSlotField = (SlotME) s; myStack = theSlotField.getAEStack(); } - catch (Throwable ignore) + catch( Throwable ignore ) { } - if ( myStack != null ) + if( myStack != null ) { List currentToolTip = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); - while (currentToolTip.size() > 1) + while( currentToolTip.size() > 1 ) currentToolTip.remove( 1 ); - currentToolTip.add( GuiText.Installed.getLocal() + ": " + (myStack.getStackSize()) ); + currentToolTip.add( GuiText.Installed.getLocal() + ": " + ( myStack.getStackSize() ) ); currentToolTip.add( GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong( myStack.getCountRequestable(), true ) ); this.drawTooltip( x, y, 0, join( currentToolTip, "\n" ) ); diff --git a/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java b/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java index 7cce249d9..0c3ed2192 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java +++ b/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import java.io.IOException; import net.minecraft.client.gui.GuiButton; @@ -32,27 +33,29 @@ import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; + public class GuiNetworkTool extends AEBaseGui { GuiToggleButton tFacades; - public GuiNetworkTool(InventoryPlayer inventoryPlayer, INetworkTool te) { + public GuiNetworkTool( InventoryPlayer inventoryPlayer, INetworkTool te ) + { super( new ContainerNetworkTool( inventoryPlayer, te ) ); this.ySize = 166; } @Override - protected void actionPerformed(GuiButton btn) + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); try { - if ( btn == this.tFacades ) + if( btn == this.tFacades ) NetworkHandler.instance.sendToServer( new PacketValueConfig( "NetworkTool", "Toggle" ) ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } @@ -69,20 +72,19 @@ public class GuiNetworkTool extends AEBaseGui } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - this.bindTexture( "guis/toolbox.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - if ( this.tFacades != null ) - this.tFacades.setState( ((ContainerNetworkTool) this.inventorySlots).facadeMode ); + if( this.tFacades != null ) + this.tFacades.setState( ( (ContainerNetworkTool) this.inventorySlots ).facadeMode ); this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.NetworkTool.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/toolbox.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java b/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java index a951d92c2..f3a29b3be 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import java.io.IOException; import net.minecraft.client.gui.GuiButton; @@ -36,6 +37,7 @@ import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; + public class GuiPatternTerm extends GuiMEMonitorable { @@ -47,50 +49,37 @@ public class GuiPatternTerm extends GuiMEMonitorable GuiImgButton encodeBtn; GuiImgButton clearBtn; - @Override - public void initGui() + public GuiPatternTerm( InventoryPlayer inventoryPlayer, ITerminalHost te ) { - super.initGui(); - this.buttonList.add( this.tabCraftButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.crafting_table ), - GuiText.CraftingPattern.getLocal(), itemRender ) ); - this.buttonList.add( this.tabProcessButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.furnace ), - GuiText.ProcessingPattern.getLocal(), itemRender ) ); - - // buttonList.add( substitutionsBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, - // Settings.ACTIONS, ActionItems.SUBSTITUTION ) ); - // substitutionsBtn.halfSize = true; - - this.buttonList.add( this.clearBtn = new GuiImgButton( this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE ) ); - this.clearBtn.halfSize = true; - - this.buttonList.add( this.encodeBtn = new GuiImgButton( this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE ) ); + super( inventoryPlayer, te, new ContainerPatternTerm( inventoryPlayer, te ) ); + this.container = (ContainerPatternTerm) this.inventorySlots; + this.reservedSpace = 81; } @Override - protected void actionPerformed(GuiButton btn) + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); try { - if ( this.tabCraftButton == btn || this.tabProcessButton == btn ) + if( this.tabCraftButton == btn || this.tabProcessButton == btn ) { NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.CraftMode", this.tabProcessButton == btn ? "1" : "0" ) ); } - if ( this.encodeBtn == btn ) + if( this.encodeBtn == btn ) { NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Encode", "1" ) ); } - if ( this.clearBtn == btn ) + if( this.clearBtn == btn ) { NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Clear", "1" ) ); } - } - catch (IOException e) + catch( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); @@ -103,32 +92,26 @@ public class GuiPatternTerm extends GuiMEMonitorable } @Override - protected void repositionSlot(AppEngSlot s) + public void initGui() { - if ( s.isPlayerSide() ) - s.yDisplayPosition = s.defY + this.ySize - 78 - 5; - else - s.yDisplayPosition = s.defY + this.ySize - 78 - 3; - } + super.initGui(); + this.buttonList.add( this.tabCraftButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.crafting_table ), GuiText.CraftingPattern.getLocal(), itemRender ) ); + this.buttonList.add( this.tabProcessButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.furnace ), GuiText.ProcessingPattern.getLocal(), itemRender ) ); - public GuiPatternTerm(InventoryPlayer inventoryPlayer, ITerminalHost te) { - super( inventoryPlayer, te, new ContainerPatternTerm( inventoryPlayer, te ) ); - this.container = (ContainerPatternTerm) this.inventorySlots; - this.reservedSpace = 81; + // buttonList.add( substitutionsBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, + // Settings.ACTIONS, ActionItems.SUBSTITUTION ) ); + // substitutionsBtn.halfSize = true; + + this.buttonList.add( this.clearBtn = new GuiImgButton( this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE ) ); + this.clearBtn.halfSize = true; + + this.buttonList.add( this.encodeBtn = new GuiImgButton( this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE ) ); } @Override - protected String getBackground() + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - if ( this.container.craftingMode ) - return "guis/pattern.png"; - return "guis/pattern2.png"; - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - if ( !this.container.craftingMode ) + if( !this.container.craftingMode ) { this.tabCraftButton.visible = false; this.tabProcessButton.visible = true; @@ -143,4 +126,20 @@ public class GuiPatternTerm extends GuiMEMonitorable this.fontRendererObj.drawString( GuiText.PatternTerminal.getLocal(), 8, this.ySize - 96 + 2 - this.reservedSpace, 4210752 ); } + @Override + protected String getBackground() + { + if( this.container.craftingMode ) + return "guis/pattern.png"; + return "guis/pattern2.png"; + } + + @Override + protected void repositionSlot( AppEngSlot s ) + { + if( s.isPlayerSide() ) + s.yDisplayPosition = s.defY + this.ySize - 78 - 5; + else + s.yDisplayPosition = s.defY + this.ySize - 78 - 3; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiPriority.java b/src/main/java/appeng/client/gui/implementations/GuiPriority.java index ef12b62a6..5c419caea 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiPriority.java +++ b/src/main/java/appeng/client/gui/implementations/GuiPriority.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import java.io.IOException; import net.minecraft.client.gui.GuiButton; @@ -48,6 +49,7 @@ import appeng.tile.misc.TileInterface; import appeng.tile.storage.TileChest; import appeng.tile.storage.TileDrive; + public class GuiPriority extends AEBaseGui { @@ -65,7 +67,8 @@ public class GuiPriority extends AEBaseGui GuiBridge OriginalGui; - public GuiPriority(InventoryPlayer inventoryPlayer, IPriorityHost te) { + public GuiPriority( InventoryPlayer inventoryPlayer, IPriorityHost te ) + { super( new ContainerPriority( inventoryPlayer, te ) ); } @@ -90,32 +93,32 @@ public class GuiPriority extends AEBaseGui this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 69, 38, 20, "-" + d ) ); ItemStack myIcon = null; - Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); + Object target = ( (AEBaseContainer) this.inventorySlots ).getTarget(); final IDefinitions definitions = AEApi.instance().definitions(); final IParts parts = definitions.parts(); final IBlocks blocks = definitions.blocks(); - if ( target instanceof PartStorageBus ) + if( target instanceof PartStorageBus ) { - for ( ItemStack storageBusStack :parts.storageBus().maybeStack( 1 ).asSet() ) + for( ItemStack storageBusStack : parts.storageBus().maybeStack( 1 ).asSet() ) { myIcon = storageBusStack; } this.OriginalGui = GuiBridge.GUI_STORAGEBUS; } - if ( target instanceof PartFormationPlane ) + if( target instanceof PartFormationPlane ) { - for ( ItemStack formationPlaneStack : parts.formationPlane().maybeStack( 1 ).asSet() ) + for( ItemStack formationPlaneStack : parts.formationPlane().maybeStack( 1 ).asSet() ) { myIcon = formationPlaneStack; } this.OriginalGui = GuiBridge.GUI_FORMATION_PLANE; } - if ( target instanceof TileDrive ) + if( target instanceof TileDrive ) { - for ( ItemStack driveStack : blocks.drive().maybeStack( 1 ).asSet() ) + for( ItemStack driveStack : blocks.drive().maybeStack( 1 ).asSet() ) { myIcon = driveStack; } @@ -123,9 +126,9 @@ public class GuiPriority extends AEBaseGui this.OriginalGui = GuiBridge.GUI_DRIVE; } - if ( target instanceof TileChest ) + if( target instanceof TileChest ) { - for ( ItemStack chestStack : blocks.chest().maybeStack( 1 ).asSet() ) + for( ItemStack chestStack : blocks.chest().maybeStack( 1 ).asSet() ) { myIcon = chestStack; } @@ -133,9 +136,9 @@ public class GuiPriority extends AEBaseGui this.OriginalGui = GuiBridge.GUI_CHEST; } - if ( target instanceof TileInterface ) + if( target instanceof TileInterface ) { - for ( ItemStack interfaceStack : blocks.iface().maybeStack( 1 ).asSet() ) + for( ItemStack interfaceStack : blocks.iface().maybeStack( 1 ).asSet() ) { myIcon = interfaceStack; } @@ -143,16 +146,16 @@ public class GuiPriority extends AEBaseGui this.OriginalGui = GuiBridge.GUI_INTERFACE; } - if ( target instanceof PartInterface ) + if( target instanceof PartInterface ) { - for ( ItemStack interfaceStack : parts.iface().maybeStack( 1 ).asSet() ) + for( ItemStack interfaceStack : parts.iface().maybeStack( 1 ).asSet() ) { myIcon = interfaceStack; } this.OriginalGui = GuiBridge.GUI_INTERFACE; } - if ( this.OriginalGui != null && myIcon != null ) + if( this.OriginalGui != null && myIcon != null ) this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender ) ); this.priority = new GuiNumberBox( this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT, Long.class ); @@ -161,15 +164,30 @@ public class GuiPriority extends AEBaseGui this.priority.setTextColor( 0xFFFFFF ); this.priority.setVisible( true ); this.priority.setFocused( true ); - ((ContainerPriority) this.inventorySlots).setTextField( this.priority ); + ( (ContainerPriority) this.inventorySlots ).setTextField( this.priority ); } @Override - protected void actionPerformed(GuiButton btn) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.fontRendererObj.drawString( GuiText.Priority.getLocal(), 8, 6, 4210752 ); + } + + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/priority.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + + this.priority.drawTextBox(); + } + + @Override + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); - if ( btn == this.originalGuiBtn ) + if( btn == this.originalGuiBtn ) { NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); } @@ -177,27 +195,27 @@ public class GuiPriority extends AEBaseGui boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - if ( isPlus || isMinus ) + if( isPlus || isMinus ) this.addQty( this.getQty( btn ) ); } - private void addQty(int i) + private void addQty( int i ) { try { String out = this.priority.getText(); boolean fixed = false; - while (out.startsWith( "0" ) && out.length() > 1) + while( out.startsWith( "0" ) && out.length() > 1 ) { out = out.substring( 1 ); fixed = true; } - if ( fixed ) + if( fixed ) this.priority.setText( out ); - if ( out.length() == 0 ) + if( out.length() == 0 ) out = "0"; long result = Long.parseLong( out ); @@ -207,45 +225,44 @@ public class GuiPriority extends AEBaseGui NetworkHandler.instance.sendToServer( new PacketValueConfig( "PriorityHost.Priority", out ) ); } - catch(NumberFormatException e ) + catch( NumberFormatException e ) { // nope.. this.priority.setText( "0" ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } } @Override - protected void keyTyped(char character, int key) + protected void keyTyped( char character, int key ) { - if ( !this.checkHotbarKeys( key ) ) + if( !this.checkHotbarKeys( key ) ) { - if ( (key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit( character )) - && this.priority.textboxKeyTyped( character, key ) ) + if( ( key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit( character ) ) && this.priority.textboxKeyTyped( character, key ) ) { try { String out = this.priority.getText(); boolean fixed = false; - while (out.startsWith( "0" ) && out.length() > 1) + while( out.startsWith( "0" ) && out.length() > 1 ) { out = out.substring( 1 ); fixed = true; } - if ( fixed ) + if( fixed ) this.priority.setText( out ); - if ( out.length() == 0 ) + if( out.length() == 0 ) out = "0"; NetworkHandler.instance.sendToServer( new PacketValueConfig( "PriorityHost.Priority", out ) ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } @@ -257,23 +274,8 @@ public class GuiPriority extends AEBaseGui } } - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/priority.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - - this.priority.drawTextBox(); - } - protected String getBackground() { return "guis/priority.png"; } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( GuiText.Priority.getLocal(), 8, 6, 4210752 ); - } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiQNB.java b/src/main/java/appeng/client/gui/implementations/GuiQNB.java index c4b76010e..fdc659855 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiQNB.java +++ b/src/main/java/appeng/client/gui/implementations/GuiQNB.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.client.gui.AEBaseGui; @@ -25,26 +26,27 @@ import appeng.container.implementations.ContainerQNB; import appeng.core.localization.GuiText; import appeng.tile.qnb.TileQuantumBridge; + public class GuiQNB extends AEBaseGui { - public GuiQNB(InventoryPlayer inventoryPlayer, TileQuantumBridge te) { + public GuiQNB( InventoryPlayer inventoryPlayer, TileQuantumBridge te ) + { super( new ContainerQNB( inventoryPlayer, te ) ); this.ySize = 166; } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/chest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.QuantumLinkChamber.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/chest.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java b/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java index 9f710b463..7641061a1 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java +++ b/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import java.io.IOException; import net.minecraft.client.gui.GuiTextField; @@ -31,12 +32,14 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; import appeng.items.contents.QuartzKnifeObj; + public class GuiQuartzKnife extends AEBaseGui { GuiTextField name; - public GuiQuartzKnife(InventoryPlayer inventoryPlayer, QuartzKnifeObj te) { + public GuiQuartzKnife( InventoryPlayer inventoryPlayer, QuartzKnifeObj te ) + { super( new ContainerQuartzKnife( inventoryPlayer, te ) ); this.ySize = 184; } @@ -55,7 +58,14 @@ public class GuiQuartzKnife extends AEBaseGui } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.QuartzCuttingKnife.getLocal() ), 8, 6, 4210752 ); + this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); + } + + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.bindTexture( "guis/quartzknife.png" ); this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); @@ -63,17 +73,17 @@ public class GuiQuartzKnife extends AEBaseGui } @Override - protected void keyTyped(char character, int key) + protected void keyTyped( char character, int key ) { - if ( this.name.textboxKeyTyped( character, key ) ) + if( this.name.textboxKeyTyped( character, key ) ) { try { String Out = this.name.getText(); - ((ContainerQuartzKnife) this.inventorySlots).setName( Out ); + ( (ContainerQuartzKnife) this.inventorySlots ).setName( Out ); NetworkHandler.instance.sendToServer( new PacketValueConfig( "QuartzKnife.Name", Out ) ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } @@ -83,12 +93,4 @@ public class GuiQuartzKnife extends AEBaseGui super.keyTyped( character, key ); } } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.QuartzCuttingKnife.getLocal() ), 8, 6, 4210752 ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSecurity.java b/src/main/java/appeng/client/gui/implementations/GuiSecurity.java index 05b15b98d..6c5083efc 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSecurity.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSecurity.java @@ -33,10 +33,18 @@ import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; + public class GuiSecurity extends GuiMEMonitorable { - public GuiSecurity(InventoryPlayer inventoryPlayer, ITerminalHost te) { + GuiToggleButton inject; + GuiToggleButton extract; + GuiToggleButton craft; + GuiToggleButton build; + GuiToggleButton security; + + public GuiSecurity( InventoryPlayer inventoryPlayer, ITerminalHost te ) + { super( inventoryPlayer, te, new ContainerSecurity( inventoryPlayer, te ) ); this.customSortOrder = false; this.reservedSpace = 33; @@ -46,11 +54,36 @@ public class GuiSecurity extends GuiMEMonitorable this.standardSize = this.xSize; } - GuiToggleButton inject; - GuiToggleButton extract; - GuiToggleButton craft; - GuiToggleButton build; - GuiToggleButton security; + @Override + protected void actionPerformed( net.minecraft.client.gui.GuiButton btn ) + { + super.actionPerformed( btn ); + + SecurityPermissions toggleSetting = null; + + if( btn == this.inject ) + toggleSetting = SecurityPermissions.INJECT; + if( btn == this.extract ) + toggleSetting = SecurityPermissions.EXTRACT; + if( btn == this.craft ) + toggleSetting = SecurityPermissions.CRAFT; + if( btn == this.build ) + toggleSetting = SecurityPermissions.BUILD; + if( btn == this.security ) + toggleSetting = SecurityPermissions.SECURITY; + + if( toggleSetting != null ) + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "TileSecurity.ToggleOption", toggleSetting.name() ) ); + } + catch( IOException e ) + { + AELog.error( e ); + } + } + } @Override public void initGui() @@ -58,52 +91,22 @@ public class GuiSecurity extends GuiMEMonitorable super.initGui(); int top = this.guiTop + this.ySize - 116; - this.buttonList.add( this.inject = new GuiToggleButton( this.guiLeft + 56, top, 11 * 16, 12 * 16, SecurityPermissions.INJECT - .getUnlocalizedName(), SecurityPermissions.INJECT.getUnlocalizedTip() ) ); + this.buttonList.add( this.inject = new GuiToggleButton( this.guiLeft + 56, top, 11 * 16, 12 * 16, SecurityPermissions.INJECT.getUnlocalizedName(), SecurityPermissions.INJECT.getUnlocalizedTip() ) ); - this.buttonList.add( this.extract = new GuiToggleButton( this.guiLeft + 56 + 18, top, 11 * 16 + 1, 12 * 16 + 1, SecurityPermissions.EXTRACT - .getUnlocalizedName(), SecurityPermissions.EXTRACT.getUnlocalizedTip() ) ); + this.buttonList.add( this.extract = new GuiToggleButton( this.guiLeft + 56 + 18, top, 11 * 16 + 1, 12 * 16 + 1, SecurityPermissions.EXTRACT.getUnlocalizedName(), SecurityPermissions.EXTRACT.getUnlocalizedTip() ) ); - this.buttonList.add( this.craft = new GuiToggleButton( this.guiLeft + 56 + 18 * 2, top, 11 * 16 + 2, 12 * 16 + 2, SecurityPermissions.CRAFT.getUnlocalizedName(), - SecurityPermissions.CRAFT.getUnlocalizedTip() ) ); + this.buttonList.add( this.craft = new GuiToggleButton( this.guiLeft + 56 + 18 * 2, top, 11 * 16 + 2, 12 * 16 + 2, SecurityPermissions.CRAFT.getUnlocalizedName(), SecurityPermissions.CRAFT.getUnlocalizedTip() ) ); - this.buttonList.add( this.build = new GuiToggleButton( this.guiLeft + 56 + 18 * 3, top, 11 * 16 + 3, 12 * 16 + 3, SecurityPermissions.BUILD.getUnlocalizedName(), - SecurityPermissions.BUILD.getUnlocalizedTip() ) ); + this.buttonList.add( this.build = new GuiToggleButton( this.guiLeft + 56 + 18 * 3, top, 11 * 16 + 3, 12 * 16 + 3, SecurityPermissions.BUILD.getUnlocalizedName(), SecurityPermissions.BUILD.getUnlocalizedTip() ) ); - this.buttonList.add( this.security = new GuiToggleButton( this.guiLeft + 56 + 18 * 4, top, 11 * 16 + 4, 12 * 16 + 4, SecurityPermissions.SECURITY - .getUnlocalizedName(), SecurityPermissions.SECURITY.getUnlocalizedTip() ) ); + this.buttonList.add( this.security = new GuiToggleButton( this.guiLeft + 56 + 18 * 4, top, 11 * 16 + 4, 12 * 16 + 4, SecurityPermissions.SECURITY.getUnlocalizedName(), SecurityPermissions.SECURITY.getUnlocalizedTip() ) ); } @Override - protected void actionPerformed(net.minecraft.client.gui.GuiButton btn) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - super.actionPerformed( btn ); - - SecurityPermissions toggleSetting = null; - - if ( btn == this.inject ) - toggleSetting = SecurityPermissions.INJECT; - if ( btn == this.extract ) - toggleSetting = SecurityPermissions.EXTRACT; - if ( btn == this.craft ) - toggleSetting = SecurityPermissions.CRAFT; - if ( btn == this.build ) - toggleSetting = SecurityPermissions.BUILD; - if ( btn == this.security ) - toggleSetting = SecurityPermissions.SECURITY; - - if ( toggleSetting != null ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "TileSecurity.ToggleOption", toggleSetting.name() ) ); - } - catch (IOException e) - { - AELog.error( e ); - } - } - + super.drawFG( offsetX, offsetY, mouseX, mouseY ); + this.fontRendererObj.drawString( GuiText.SecurityCardEditor.getLocal(), 8, this.ySize - 96 + 1 - this.reservedSpace, 4210752 ); } @Override @@ -111,26 +114,18 @@ public class GuiSecurity extends GuiMEMonitorable { ContainerSecurity cs = (ContainerSecurity) this.inventorySlots; - this.inject.setState( (cs.security & (1 << SecurityPermissions.INJECT.ordinal())) > 0 ); - this.extract.setState( (cs.security & (1 << SecurityPermissions.EXTRACT.ordinal())) > 0 ); - this.craft.setState( (cs.security & (1 << SecurityPermissions.CRAFT.ordinal())) > 0 ); - this.build.setState( (cs.security & (1 << SecurityPermissions.BUILD.ordinal())) > 0 ); - this.security.setState( (cs.security & (1 << SecurityPermissions.SECURITY.ordinal())) > 0 ); + this.inject.setState( ( cs.security & ( 1 << SecurityPermissions.INJECT.ordinal() ) ) > 0 ); + this.extract.setState( ( cs.security & ( 1 << SecurityPermissions.EXTRACT.ordinal() ) ) > 0 ); + this.craft.setState( ( cs.security & ( 1 << SecurityPermissions.CRAFT.ordinal() ) ) > 0 ); + this.build.setState( ( cs.security & ( 1 << SecurityPermissions.BUILD.ordinal() ) ) > 0 ); + this.security.setState( ( cs.security & ( 1 << SecurityPermissions.SECURITY.ordinal() ) ) > 0 ); return "guis/security.png"; } - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.SecurityCardEditor.getLocal(), 8, this.ySize - 96 + 1 - this.reservedSpace, 4210752 ); - } - @Override public Enum getSortBy() { return SortOrder.NAME; } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java b/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java index 82c88d8b1..439b3ba83 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.client.gui.AEBaseGui; @@ -27,32 +28,33 @@ import appeng.core.localization.GuiText; import appeng.integration.IntegrationType; import appeng.tile.storage.TileSkyChest; + public class GuiSkyChest extends AEBaseGui { - public GuiSkyChest(InventoryPlayer inventoryPlayer, TileSkyChest te) { + public GuiSkyChest( InventoryPlayer inventoryPlayer, TileSkyChest te ) + { super( new ContainerSkyChest( inventoryPlayer, te ) ); this.ySize = 195; } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/skychest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.SkyChest.getLocal() ), 8, 8, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 2, 4210752 ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/skychest.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } + @Override protected boolean enableSpaceClicking() { return !AppEng.instance.isIntegrationEnabled( IntegrationType.InvTweaks ); } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java b/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java index 05a353d53..287a89586 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java @@ -33,26 +33,28 @@ import appeng.core.localization.GuiText; import appeng.tile.spatial.TileSpatialIOPort; import appeng.util.Platform; + public class GuiSpatialIOPort extends AEBaseGui { final ContainerSpatialIOPort container; GuiImgButton units; - public GuiSpatialIOPort(InventoryPlayer inventoryPlayer, TileSpatialIOPort te) { + public GuiSpatialIOPort( InventoryPlayer inventoryPlayer, TileSpatialIOPort te ) + { super( new ContainerSpatialIOPort( inventoryPlayer, te ) ); this.ySize = 199; this.container = (ContainerSpatialIOPort) this.inventorySlots; } @Override - protected void actionPerformed(GuiButton btn) + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); boolean backwards = Mouse.isButtonDown( 1 ); - if ( btn == this.units ) + if( btn == this.units ) { AEConfig.instance.nextPowerUnit( backwards ); this.units.set( AEConfig.instance.selectedPowerUnit() ); @@ -69,22 +71,21 @@ public class GuiSpatialIOPort extends AEBaseGui } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/spatialio.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong( this.container.currentPower, false ), 13, 21, 4210752 ); this.fontRendererObj.drawString( GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong( this.container.maxPower, false ), 13, 31, 4210752 ); this.fontRendererObj.drawString( GuiText.RequiredPower.getLocal() + ": " + Platform.formatPowerLong( this.container.reqPower, false ), 13, 78, 4210752 ); - this.fontRendererObj.drawString( GuiText.Efficiency.getLocal() + ": " + (((float) this.container.eff) / 100) + '%', 13, 88, 4210752 ); + this.fontRendererObj.drawString( GuiText.Efficiency.getLocal() + ": " + ( ( (float) this.container.eff ) / 100 ) + '%', 13, 88, 4210752 ); this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.SpatialIOPort.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96, 4210752 ); } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/spatialio.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java b/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java index bc4895867..ce43b725c 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import java.io.IOException; import org.lwjgl.input.Mouse; @@ -42,6 +43,7 @@ import appeng.core.sync.packets.PacketSwitchGuis; import appeng.core.sync.packets.PacketValueConfig; import appeng.parts.misc.PartStorageBus; + public class GuiStorageBus extends GuiUpgradeable { @@ -51,27 +53,12 @@ public class GuiStorageBus extends GuiUpgradeable GuiImgButton partition; GuiImgButton clear; - public GuiStorageBus(InventoryPlayer inventoryPlayer, PartStorageBus te) { + public GuiStorageBus( InventoryPlayer inventoryPlayer, PartStorageBus te ) + { super( new ContainerStorageBus( inventoryPlayer, te ) ); this.ySize = 251; } - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.StorageBus.getLocal() ), 8, 6, 4210752 ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - - if ( this.fuzzyMode != null ) - this.fuzzyMode.set( this.cvb.fzMode ); - - if ( this.storageFilter != null ) - this.storageFilter.set( ((ContainerStorageBus) this.cvb).storageFilter ); - - if ( this.rwMode != null ) - this.rwMode.set( ((ContainerStorageBus) this.cvb).rwMode ); - } - @Override protected void addButtons() { @@ -91,34 +78,19 @@ public class GuiStorageBus extends GuiUpgradeable } @Override - protected void actionPerformed(GuiButton btn) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - super.actionPerformed( btn ); + this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.StorageBus.getLocal() ), 8, 6, 4210752 ); + this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - boolean backwards = Mouse.isButtonDown( 1 ); + if( this.fuzzyMode != null ) + this.fuzzyMode.set( this.cvb.fzMode ); - try - { - if ( btn == this.partition ) - NetworkHandler.instance.sendToServer( new PacketValueConfig( "StorageBus.Action", "Partition" ) ); + if( this.storageFilter != null ) + this.storageFilter.set( ( (ContainerStorageBus) this.cvb ).storageFilter ); - else if ( btn == this.clear ) - NetworkHandler.instance.sendToServer( new PacketValueConfig( "StorageBus.Action", "Clear" ) ); - - else if ( btn == this.priority ) - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - - else if ( btn == this.rwMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.rwMode.getSetting(), backwards ) ); - - else if ( btn == this.storageFilter ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.storageFilter.getSetting(), backwards ) ); - - } - catch (IOException e) - { - AELog.error( e ); - } + if( this.rwMode != null ) + this.rwMode.set( ( (ContainerStorageBus) this.cvb ).rwMode ); } @Override @@ -127,4 +99,33 @@ public class GuiStorageBus extends GuiUpgradeable return "guis/storagebus.png"; } + @Override + protected void actionPerformed( GuiButton btn ) + { + super.actionPerformed( btn ); + + boolean backwards = Mouse.isButtonDown( 1 ); + + try + { + if( btn == this.partition ) + NetworkHandler.instance.sendToServer( new PacketValueConfig( "StorageBus.Action", "Partition" ) ); + + else if( btn == this.clear ) + NetworkHandler.instance.sendToServer( new PacketValueConfig( "StorageBus.Action", "Clear" ) ); + + else if( btn == this.priority ) + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); + + else if( btn == this.rwMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.rwMode.getSetting(), backwards ) ); + + else if( btn == this.storageFilter ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.storageFilter.getSetting(), backwards ) ); + } + catch( IOException e ) + { + AELog.error( e ); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java b/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java index f5b814be1..25ea0ad1a 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java +++ b/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import org.lwjgl.input.Mouse; import net.minecraft.client.gui.GuiButton; @@ -37,6 +38,7 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.parts.automation.PartImportBus; + public class GuiUpgradeable extends AEBaseGui { @@ -47,11 +49,13 @@ public class GuiUpgradeable extends AEBaseGui GuiImgButton fuzzyMode; GuiImgButton craftMode; - public GuiUpgradeable(InventoryPlayer inventoryPlayer, IUpgradeableHost te) { + public GuiUpgradeable( InventoryPlayer inventoryPlayer, IUpgradeableHost te ) + { this( new ContainerUpgradeable( inventoryPlayer, te ) ); } - public GuiUpgradeable(ContainerUpgradeable te) { + public GuiUpgradeable( ContainerUpgradeable te ) + { super( te ); this.cvb = te; @@ -60,6 +64,11 @@ public class GuiUpgradeable extends AEBaseGui this.ySize = 184; } + protected boolean hasToolbox() + { + return ( (ContainerUpgradeable) this.inventorySlots ).hasToolbox(); + } + @Override public void initGui() { @@ -79,43 +88,42 @@ public class GuiUpgradeable extends AEBaseGui } @Override - protected void actionPerformed(GuiButton btn) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { - super.actionPerformed( btn ); + this.fontRendererObj.drawString( this.getGuiDisplayName( this.getName().getLocal() ), 8, 6, 4210752 ); + this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - boolean backwards = Mouse.isButtonDown( 1 ); + if( this.redstoneMode != null ) + this.redstoneMode.set( this.cvb.rsMode ); - if ( btn == this.redstoneMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.redstoneMode.getSetting(), backwards ) ); + if( this.fuzzyMode != null ) + this.fuzzyMode.set( this.cvb.fzMode ); - if ( btn == this.craftMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.craftMode.getSetting(), backwards ) ); - - if ( btn == this.fuzzyMode ) - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.fuzzyMode.getSetting(), backwards ) ); - } - - protected boolean hasToolbox() - { - return ((ContainerUpgradeable) this.inventorySlots).hasToolbox(); + if( this.craftMode != null ) + this.craftMode.set( this.cvb.cMode ); } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.handleButtonVisibility(); this.bindTexture( this.getBackground() ); this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - if ( this.drawUpgrades() ) + if( this.drawUpgrades() ) this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvb.availableUpgrades() * 18 ); - if ( this.hasToolbox() ) + if( this.hasToolbox() ) this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 ); } - protected boolean drawUpgrades() + protected void handleButtonVisibility() { - return true; + if( this.redstoneMode != null ) + this.redstoneMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ); + if( this.fuzzyMode != null ) + this.fuzzyMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ); + if( this.craftMode != null ) + this.craftMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ); } protected String getBackground() @@ -123,30 +131,9 @@ public class GuiUpgradeable extends AEBaseGui return "guis/bus.png"; } - protected void handleButtonVisibility() + protected boolean drawUpgrades() { - if ( this.redstoneMode != null ) - this.redstoneMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ); - if ( this.fuzzyMode != null ) - this.fuzzyMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ); - if ( this.craftMode != null ) - this.craftMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( this.getName().getLocal() ), 8, 6, 4210752 ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - - if ( this.redstoneMode != null ) - this.redstoneMode.set( this.cvb.rsMode ); - - if ( this.fuzzyMode != null ) - this.fuzzyMode.set( this.cvb.fzMode ); - - if ( this.craftMode != null ) - this.craftMode.set( this.cvb.cMode ); + return true; } protected GuiText getName() @@ -154,4 +141,20 @@ public class GuiUpgradeable extends AEBaseGui return this.bc instanceof PartImportBus ? GuiText.ImportBus : GuiText.ExportBus; } + @Override + protected void actionPerformed( GuiButton btn ) + { + super.actionPerformed( btn ); + + boolean backwards = Mouse.isButtonDown( 1 ); + + if( btn == this.redstoneMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.redstoneMode.getSetting(), backwards ) ); + + if( btn == this.craftMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.craftMode.getSetting(), backwards ) ); + + if( btn == this.fuzzyMode ) + NetworkHandler.instance.sendToServer( new PacketConfigButton( this.fuzzyMode.getSetting(), backwards ) ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java b/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java index d1ada2f5c..4cbde2895 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java +++ b/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import org.lwjgl.opengl.GL11; import net.minecraft.entity.player.InventoryPlayer; @@ -29,13 +30,14 @@ import appeng.container.implementations.ContainerVibrationChamber; import appeng.core.localization.GuiText; import appeng.tile.misc.TileVibrationChamber; + public class GuiVibrationChamber extends AEBaseGui { final ContainerVibrationChamber cvc; GuiProgressBar pb; - public GuiVibrationChamber(InventoryPlayer inventoryPlayer, TileVibrationChamber te) + public GuiVibrationChamber( InventoryPlayer inventoryPlayer, TileVibrationChamber te ) { super( new ContainerVibrationChamber( inventoryPlayer, te ) ); this.cvc = (ContainerVibrationChamber) this.inventorySlots; @@ -52,16 +54,7 @@ public class GuiVibrationChamber extends AEBaseGui } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/vibchamber.png" ); - this.pb.xPosition = 99 + this.guiLeft; - this.pb.yPosition = 36 + this.guiTop; - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.VibrationChamber.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); @@ -71,7 +64,7 @@ public class GuiVibrationChamber extends AEBaseGui this.pb.setFullMsg( this.cvc.aePerTick * this.cvc.getCurrentProgress() / 100 + " ae/t" ); - if ( this.cvc.getCurrentProgress() > 0 ) + if( this.cvc.getCurrentProgress() > 0 ) { int i1 = this.cvc.getCurrentProgress(); this.bindTexture( "guis/vibchamber.png" ); @@ -80,4 +73,12 @@ public class GuiVibrationChamber extends AEBaseGui } } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/vibchamber.png" ); + this.pb.xPosition = 99 + this.guiLeft; + this.pb.yPosition = 36 + this.guiTop; + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiWireless.java b/src/main/java/appeng/client/gui/implementations/GuiWireless.java index b2b4ba2de..ded8dd267 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiWireless.java +++ b/src/main/java/appeng/client/gui/implementations/GuiWireless.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; + import org.lwjgl.input.Mouse; import net.minecraft.client.gui.GuiButton; @@ -32,19 +33,26 @@ import appeng.core.localization.GuiText; import appeng.tile.networking.TileWireless; import appeng.util.Platform; + public class GuiWireless extends AEBaseGui { GuiImgButton units; + public GuiWireless( InventoryPlayer inventoryPlayer, TileWireless te ) + { + super( new ContainerWireless( inventoryPlayer, te ) ); + this.ySize = 166; + } + @Override - protected void actionPerformed(GuiButton btn) + protected void actionPerformed( GuiButton btn ) { super.actionPerformed( btn ); boolean backwards = Mouse.isButtonDown( 1 ); - if ( btn == this.units ) + if( btn == this.units ) { AEConfig.instance.nextPowerUnit( backwards ); this.units.set( AEConfig.instance.selectedPowerUnit() ); @@ -60,36 +68,30 @@ public class GuiWireless extends AEBaseGui this.buttonList.add( this.units ); } - public GuiWireless(InventoryPlayer inventoryPlayer, TileWireless te) { - super( new ContainerWireless( inventoryPlayer, te ) ); - this.ySize = 166; - } - @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/wireless.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Wireless.getLocal() ), 8, 6, 4210752 ); this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); ContainerWireless cw = (ContainerWireless) this.inventorySlots; - if ( cw.range > 0 ) + if( cw.range > 0 ) { - String firstMessage = GuiText.Range.getLocal() + ": " + (cw.range / 10.0) + " m"; + String firstMessage = GuiText.Range.getLocal() + ": " + ( cw.range / 10.0 ) + " m"; String secondMessage = GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong( cw.drain, true ); int strWidth = Math.max( this.fontRendererObj.getStringWidth( firstMessage ), this.fontRendererObj.getStringWidth( secondMessage ) ); - int cOffset = (this.xSize / 2) - (strWidth / 2); + int cOffset = ( this.xSize / 2 ) - ( strWidth / 2 ); this.fontRendererObj.drawString( firstMessage, cOffset, 20, 4210752 ); this.fontRendererObj.drawString( secondMessage, cOffset, 20 + 12, 4210752 ); } } + @Override + public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) + { + this.bindTexture( "guis/wireless.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java b/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java index a58af12ac..c8c40a601 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java @@ -18,14 +18,17 @@ package appeng.client.gui.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.api.implementations.guiobjects.IPortableCell; + public class GuiWirelessTerm extends GuiMEPortableCell { - public GuiWirelessTerm(InventoryPlayer inventoryPlayer, IPortableCell te) { + public GuiWirelessTerm( InventoryPlayer inventoryPlayer, IPortableCell te ) + { super( inventoryPlayer, te ); this.maxRows = Integer.MAX_VALUE; } diff --git a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java index c9653a1d4..26fa7ccbb 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java @@ -72,7 +72,7 @@ public class GuiImgButton extends GuiButton implements ITooltip this.width = 16; this.height = 16; - if ( appearances == null ) + if( appearances == null ) { appearances = new HashMap(); this.registerApp( 16 * 7, Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH, ButtonToolTips.CondenserOutput, ButtonToolTips.Trash ); @@ -165,7 +165,7 @@ public class GuiImgButton extends GuiButton implements ITooltip { ButtonAppearance a = new ButtonAppearance(); a.displayName = title.getUnlocalized(); - a.displayValue = ( String ) ( hint instanceof String ? hint : ( ( ButtonToolTips ) hint ).getUnlocalized() ); + a.displayValue = (String) ( hint instanceof String ? hint : ( (ButtonToolTips) hint ).getUnlocalized() ); a.index = iconIndex; appearances.put( new EnumPair( setting, val ), a ); } @@ -179,11 +179,11 @@ public class GuiImgButton extends GuiButton implements ITooltip @Override public void drawButton( Minecraft par1Minecraft, int par2, int par3 ) { - if ( this.visible ) + if( this.visible ) { int iconIndex = this.getIconIndex(); - if ( this.halfSize ) + if( this.halfSize ) { this.width = 8; this.height = 8; @@ -192,7 +192,7 @@ public class GuiImgButton extends GuiButton implements ITooltip GL11.glTranslatef( this.xPosition, this.yPosition, 0.0F ); GL11.glScalef( 0.5f, 0.5f, 0.5f ); - if ( this.enabled ) + if( this.enabled ) GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); else GL11.glColor4f( 0.5f, 0.5f, 0.5f, 1.0f ); @@ -200,7 +200,7 @@ public class GuiImgButton extends GuiButton implements ITooltip par1Minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height; - int uv_y = ( int ) Math.floor( iconIndex / 16 ); + int uv_y = (int) Math.floor( iconIndex / 16 ); int uv_x = iconIndex - uv_y * 16; this.drawTexturedModalRect( 0, 0, 256 - 16, 256 - 16, 16, 16 ); @@ -211,7 +211,7 @@ public class GuiImgButton extends GuiButton implements ITooltip } else { - if ( this.enabled ) + if( this.enabled ) GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); else GL11.glColor4f( 0.5f, 0.5f, 0.5f, 1.0f ); @@ -219,7 +219,7 @@ public class GuiImgButton extends GuiButton implements ITooltip par1Minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height; - int uv_y = ( int ) Math.floor( iconIndex / 16 ); + int uv_y = (int) Math.floor( iconIndex / 16 ); int uv_x = iconIndex - uv_y * 16; this.drawTexturedModalRect( this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16 ); @@ -232,10 +232,10 @@ public class GuiImgButton extends GuiButton implements ITooltip private int getIconIndex() { - if ( this.buttonSetting != null && this.currentValue != null ) + if( this.buttonSetting != null && this.currentValue != null ) { ButtonAppearance app = appearances.get( new EnumPair( this.buttonSetting, this.currentValue ) ); - if ( app == null ) + if( app == null ) return 256 - 1; return app.index; } @@ -244,7 +244,7 @@ public class GuiImgButton extends GuiButton implements ITooltip public Settings getSetting() { - return ( Settings ) this.buttonSetting; + return (Settings) this.buttonSetting; } public Enum getCurrentValue() @@ -258,36 +258,36 @@ public class GuiImgButton extends GuiButton implements ITooltip String displayName = null; String displayValue = null; - if ( this.buttonSetting != null && this.currentValue != null ) + if( this.buttonSetting != null && this.currentValue != null ) { ButtonAppearance buttonAppearance = appearances.get( new EnumPair( this.buttonSetting, this.currentValue ) ); - if ( buttonAppearance == null ) + if( buttonAppearance == null ) return "No Such Message"; displayName = buttonAppearance.displayName; displayValue = buttonAppearance.displayValue; } - if ( displayName != null ) + if( displayName != null ) { String name = StatCollector.translateToLocal( displayName ); String value = StatCollector.translateToLocal( displayValue ); - if ( name == null || name.isEmpty() ) + if( name == null || name.isEmpty() ) name = displayName; - if ( value == null || value.isEmpty() ) + if( value == null || value.isEmpty() ) value = displayValue; - if ( this.fillVar != null ) + if( this.fillVar != null ) value = COMPILE.matcher( value ).replaceFirst( this.fillVar ); value = PATTERN_NEW_LINE.matcher( value ).replaceAll( "\n" ); StringBuilder sb = new StringBuilder( value ); int i = sb.lastIndexOf( "\n" ); - if ( i <= 0 ) + if( i <= 0 ) i = 0; - while ( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) + while( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) { sb.replace( i, i + 1, "\n" ); } @@ -329,7 +329,7 @@ public class GuiImgButton extends GuiButton implements ITooltip public void set( Enum e ) { - if ( this.currentValue != e ) + if( this.currentValue != e ) { this.currentValue = e; } @@ -356,15 +356,16 @@ public class GuiImgButton extends GuiButton implements ITooltip @Override public boolean equals( Object obj ) { - if ( obj == null ) + if( obj == null ) return false; - if ( this.getClass() != obj.getClass() ) + if( this.getClass() != obj.getClass() ) return false; - EnumPair other = ( EnumPair ) obj; + EnumPair other = (EnumPair) obj; return other.setting == this.setting && other.value == this.value; } } + private static class ButtonAppearance { public int index; diff --git a/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java b/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java index f480d9430..90af80db7 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java +++ b/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java @@ -18,6 +18,7 @@ package appeng.client.gui.widgets; + import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; @@ -27,31 +28,30 @@ public class GuiNumberBox extends GuiTextField final Class type; - public GuiNumberBox(FontRenderer p_i1032_1_, int p_i1032_2_, int p_i1032_3_, int p_i1032_4_, int p_i1032_5_,Class type) { + public GuiNumberBox( FontRenderer p_i1032_1_, int p_i1032_2_, int p_i1032_3_, int p_i1032_4_, int p_i1032_5_, Class type ) + { super( p_i1032_1_, p_i1032_2_, p_i1032_3_, p_i1032_4_, p_i1032_5_ ); this.type = type; } @Override - public void writeText(String p_146191_1_) + public void writeText( String p_146191_1_ ) { String original = this.getText(); super.writeText( p_146191_1_ ); try { - if ( this.type == int.class || this.type == Integer.class ) + if( this.type == int.class || this.type == Integer.class ) Integer.parseInt( this.getText() ); - else if ( this.type == long.class || this.type == Long.class ) + else if( this.type == long.class || this.type == Long.class ) Long.parseLong( this.getText() ); - else if ( this.type == double.class || this.type == Double.class ) + else if( this.type == double.class || this.type == Double.class ) Double.parseDouble( this.getText() ); } - catch(NumberFormatException e ) + catch( NumberFormatException e ) { this.setText( original ); } } - - } diff --git a/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java b/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java index e4e13ca0c..b78e5e62a 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java +++ b/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java @@ -26,29 +26,24 @@ import net.minecraft.util.ResourceLocation; import appeng.container.interfaces.IProgressProvider; import appeng.core.localization.GuiText; + public class GuiProgressBar extends GuiButton implements ITooltip { - public enum Direction - { - HORIZONTAL, VERTICAL - } - private final IProgressProvider source; private final ResourceLocation texture; private final int fill_u; private final int fill_v; private final Direction layout; - - private String fullMsg; private final String titleName; + private String fullMsg; - public GuiProgressBar(IProgressProvider source, String texture, int posX, int posY, int u, int y, int _width, int _height, Direction dir) + public GuiProgressBar( IProgressProvider source, String texture, int posX, int posY, int u, int y, int _width, int _height, Direction dir ) { this( source, texture, posX, posY, u, y, _width, _height, dir, null ); } - public GuiProgressBar(IProgressProvider source, String texture, int posX, int posY, int u, int y, int _width, int _height, Direction dir, String title) + public GuiProgressBar( IProgressProvider source, String texture, int posX, int posY, int u, int y, int _width, int _height, Direction dir, String title ) { super( posX, posY, _width, "" ); this.source = source; @@ -64,22 +59,22 @@ public class GuiProgressBar extends GuiButton implements ITooltip } @Override - public void drawButton(Minecraft par1Minecraft, int par2, int par3) + public void drawButton( Minecraft par1Minecraft, int par2, int par3 ) { - if ( this.visible ) + if( this.visible ) { par1Minecraft.getTextureManager().bindTexture( this.texture ); int max = this.source.getMaxProgress(); int current = this.source.getCurrentProgress(); - if ( this.layout == Direction.VERTICAL ) + if( this.layout == Direction.VERTICAL ) { - int diff = this.height - (max > 0 ? (this.height * current) / max : 0); + int diff = this.height - ( max > 0 ? ( this.height * current ) / max : 0 ); this.drawTexturedModalRect( this.xPosition, this.yPosition + diff, this.fill_u, this.fill_v + diff, this.width, this.height - diff ); } else { - int diff = this.width - (max > 0 ? (this.width * current) / max : 0); + int diff = this.width - ( max > 0 ? ( this.width * current ) / max : 0 ); this.drawTexturedModalRect( this.xPosition, this.yPosition, this.fill_u + diff, this.fill_v, this.width - diff, this.height ); } @@ -87,7 +82,7 @@ public class GuiProgressBar extends GuiButton implements ITooltip } } - public void setFullMsg(String msg) + public void setFullMsg( String msg ) { this.fullMsg = msg; } @@ -95,10 +90,10 @@ public class GuiProgressBar extends GuiButton implements ITooltip @Override public String getMessage() { - if ( this.fullMsg != null ) + if( this.fullMsg != null ) return this.fullMsg; - return (this.titleName != null ? this.titleName : "") + '\n' + this.source.getCurrentProgress() + ' ' + GuiText.Of.getLocal() + ' ' + this.source.getMaxProgress(); + return ( this.titleName != null ? this.titleName : "" ) + '\n' + this.source.getCurrentProgress() + ' ' + GuiText.Of.getLocal() + ' ' + this.source.getMaxProgress(); } @Override @@ -131,4 +126,8 @@ public class GuiProgressBar extends GuiButton implements ITooltip return true; } + public enum Direction + { + HORIZONTAL, VERTICAL + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java b/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java index 5d442be1f..5d3c59627 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java +++ b/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java @@ -18,10 +18,12 @@ package appeng.client.gui.widgets; + import org.lwjgl.opengl.GL11; import appeng.client.gui.AEBaseGui; + public class GuiScrollbar implements IScrollSource { @@ -35,23 +37,18 @@ public class GuiScrollbar implements IScrollSource private int minScroll = 0; private int currentScroll = 0; - private void applyRange() - { - this.currentScroll = Math.max( Math.min( this.currentScroll, this.maxScroll ), this.minScroll ); - } - - public void draw(AEBaseGui g) + public void draw( AEBaseGui g ) { g.bindTexture( "minecraft", "gui/container/creative_inventory/tabs.png" ); GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - if ( this.getRange() == 0 ) + if( this.getRange() == 0 ) { g.drawTexturedModalRect( this.displayX, this.displayY, 232 + this.width, 0, this.width, 15 ); } else { - int offset = (this.currentScroll - this.minScroll) * (this.height - 15) / this.getRange(); + int offset = ( this.currentScroll - this.minScroll ) * ( this.height - 15 ) / this.getRange(); g.drawTexturedModalRect( this.displayX, offset + this.displayY, 232, 0, this.width, 15 ); } } @@ -66,85 +63,89 @@ public class GuiScrollbar implements IScrollSource return this.displayX; } + public GuiScrollbar setLeft( int v ) + { + this.displayX = v; + return this; + } + public int getTop() { return this.displayY; } + public GuiScrollbar setTop( int v ) + { + this.displayY = v; + return this; + } + public int getWidth() { return this.width; } - public int getHeight() - { - return this.height; - } - - public GuiScrollbar setLeft(int v) - { - this.displayX = v; - return this; - } - - public GuiScrollbar setTop(int v) - { - this.displayY = v; - return this; - } - - public GuiScrollbar setWidth(int v) + public GuiScrollbar setWidth( int v ) { this.width = v; return this; } - public GuiScrollbar setHeight(int v) + public int getHeight() + { + return this.height; + } + + public GuiScrollbar setHeight( int v ) { this.height = v; return this; } - public void setRange(int min, int max, int pageSize) + public void setRange( int min, int max, int pageSize ) { this.minScroll = min; this.maxScroll = max; this.pageSize = pageSize; - if ( this.minScroll > this.maxScroll ) + if( this.minScroll > this.maxScroll ) this.maxScroll = this.minScroll; this.applyRange(); } + private void applyRange() + { + this.currentScroll = Math.max( Math.min( this.currentScroll, this.maxScroll ), this.minScroll ); + } + @Override public int getCurrentScroll() { return this.currentScroll; } - public void click(AEBaseGui aeBaseGui, int x, int y) + public void click( AEBaseGui aeBaseGui, int x, int y ) { - if ( this.getRange() == 0 ) + if( this.getRange() == 0 ) return; - if ( x > this.displayX && x <= this.displayX + this.width ) + if( x > this.displayX && x <= this.displayX + this.width ) { - if ( y > this.displayY && y <= this.displayY + this.height ) + if( y > this.displayY && y <= this.displayY + this.height ) { - this.currentScroll = (y - this.displayY); - this.currentScroll = this.minScroll + ((this.currentScroll * 2 * this.getRange() / this.height)); - this.currentScroll = (this.currentScroll + 1) >> 1; + this.currentScroll = ( y - this.displayY ); + this.currentScroll = this.minScroll + ( ( this.currentScroll * 2 * this.getRange() / this.height ) ); + this.currentScroll = ( this.currentScroll + 1 ) >> 1; this.applyRange(); } } } - public void wheel(int delta) + public void wheel( int delta ) { delta = Math.max( Math.min( -delta, 1 ), -1 ); this.currentScroll += delta * this.pageSize; this.applyRange(); } - } diff --git a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java index 48fef12e1..ef10a2500 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java @@ -56,11 +56,11 @@ public class GuiTabButton extends GuiButton implements ITooltip /** * Using itemstack as an icon * - * @param x x pos of button - * @param y y pos of button - * @param ico used icon + * @param x x pos of button + * @param y y pos of button + * @param ico used icon * @param message mouse over message - * @param ir renderer + * @param ir renderer */ public GuiTabButton( int x, int y, ItemStack ico, String message, RenderItem ir ) { @@ -77,7 +77,7 @@ public class GuiTabButton extends GuiButton implements ITooltip @Override public void drawButton( Minecraft minecraft, int x, int y ) { - if ( this.visible ) + if( this.visible ) { GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); @@ -89,9 +89,9 @@ public class GuiTabButton extends GuiButton implements ITooltip this.drawTexturedModalRect( this.xPosition, this.yPosition, uv_x * 16, 0, 25, 22 ); - if ( this.myIcon >= 0 ) + if( this.myIcon >= 0 ) { - int uv_y = ( int ) Math.floor( this.myIcon / 16 ); + int uv_y = (int) Math.floor( this.myIcon / 16 ); uv_x = this.myIcon - uv_y * 16; this.drawTexturedModalRect( offsetX + this.xPosition + 3, this.yPosition + 3, uv_x * 16, uv_y * 16, 16, 16 ); @@ -99,7 +99,7 @@ public class GuiTabButton extends GuiButton implements ITooltip this.mouseDragged( minecraft, x, y ); - if ( this.myItem != null ) + if( this.myItem != null ) { this.zLevel = 100.0F; this.itemRenderer.zLevel = 100.0F; diff --git a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java index 85f1c1c03..851e59c50 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java @@ -62,7 +62,7 @@ public class GuiToggleButton extends GuiButton implements ITooltip @Override public void drawButton( Minecraft par1Minecraft, int par2, int par3 ) { - if ( this.visible ) + if( this.visible ) { int iconIndex = this.getIconIndex(); @@ -70,7 +70,7 @@ public class GuiToggleButton extends GuiButton implements ITooltip par1Minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height; - int uv_y = ( int ) Math.floor( iconIndex / 16 ); + int uv_y = (int) Math.floor( iconIndex / 16 ); int uv_x = iconIndex - uv_y * 16; this.drawTexturedModalRect( this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16 ); @@ -87,23 +87,23 @@ public class GuiToggleButton extends GuiButton implements ITooltip @Override public String getMessage() { - if ( this.displayName != null ) + if( this.displayName != null ) { String name = StatCollector.translateToLocal( this.displayName ); String value = StatCollector.translateToLocal( this.displayHint ); - if ( name == null || name.isEmpty() ) + if( name == null || name.isEmpty() ) name = this.displayName; - if ( value == null || value.isEmpty() ) + if( value == null || value.isEmpty() ) value = this.displayHint; value = PATTERN_NEW_LINE.matcher( value ).replaceAll( "\n" ); StringBuilder sb = new StringBuilder( value ); int i = sb.lastIndexOf( "\n" ); - if ( i <= 0 ) + if( i <= 0 ) i = 0; - while ( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) + while( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) { sb.replace( i, i + 1, "\n" ); } diff --git a/src/main/java/appeng/client/gui/widgets/IScrollSource.java b/src/main/java/appeng/client/gui/widgets/IScrollSource.java index 3dccef39b..10829091b 100644 --- a/src/main/java/appeng/client/gui/widgets/IScrollSource.java +++ b/src/main/java/appeng/client/gui/widgets/IScrollSource.java @@ -18,9 +18,9 @@ package appeng.client.gui.widgets; + public interface IScrollSource { int getCurrentScroll(); - } diff --git a/src/main/java/appeng/client/gui/widgets/ISortSource.java b/src/main/java/appeng/client/gui/widgets/ISortSource.java index 7269b1889..534dcb0dc 100644 --- a/src/main/java/appeng/client/gui/widgets/ISortSource.java +++ b/src/main/java/appeng/client/gui/widgets/ISortSource.java @@ -18,9 +18,11 @@ package appeng.client.gui.widgets; + import appeng.api.config.SortDir; import appeng.api.config.ViewItems; + public interface ISortSource { @@ -38,5 +40,4 @@ public interface ISortSource * @return {@link ViewItems} */ Enum getSortDisplay(); - } diff --git a/src/main/java/appeng/client/gui/widgets/ITooltip.java b/src/main/java/appeng/client/gui/widgets/ITooltip.java index 0aa45b0bb..232992ac6 100644 --- a/src/main/java/appeng/client/gui/widgets/ITooltip.java +++ b/src/main/java/appeng/client/gui/widgets/ITooltip.java @@ -18,9 +18,9 @@ package appeng.client.gui.widgets; + /** * AEBaseGui controlled Tooltip Interface. - * */ public interface ITooltip { @@ -64,5 +64,4 @@ public interface ITooltip * @return true if button being drawn */ boolean isVisible(); - } diff --git a/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java b/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java index d765a015f..8e09092f7 100644 --- a/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java +++ b/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java @@ -22,6 +22,7 @@ package appeng.client.gui.widgets; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; + /** * A modified version of the Minecraft text field. * You can initialize it over the full element span. @@ -44,10 +45,10 @@ public class MEGuiTextField extends GuiTextField * Pays attention to the '_' caret. * * @param fontRenderer renderer for the strings - * @param xPos absolute left position - * @param yPos absolute top position - * @param width absolute width - * @param height absolute height + * @param xPos absolute left position + * @param yPos absolute top position + * @param width absolute width + * @param height absolute height */ public MEGuiTextField( FontRenderer fontRenderer, int xPos, int yPos, int width, int height ) { diff --git a/src/main/java/appeng/client/me/ClientDCInternalInv.java b/src/main/java/appeng/client/me/ClientDCInternalInv.java index 8520a4b6d..5289b65a6 100644 --- a/src/main/java/appeng/client/me/ClientDCInternalInv.java +++ b/src/main/java/appeng/client/me/ClientDCInternalInv.java @@ -18,11 +18,13 @@ package appeng.client.me; + import net.minecraft.util.StatCollector; import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.ItemSorters; + public class ClientDCInternalInv implements Comparable { @@ -31,7 +33,8 @@ public class ClientDCInternalInv implements Comparable final public long id; final public long sortBy; - public ClientDCInternalInv(int size, long id, long sortBy, String unlocalizedName) { + public ClientDCInternalInv( int size, long id, long sortBy, String unlocalizedName ) + { this.inv = new AppEngInternalInventory( null, size ); this.unlocalizedName = unlocalizedName; this.id = id; @@ -41,15 +44,14 @@ public class ClientDCInternalInv implements Comparable public String getName() { String s = StatCollector.translateToLocal( this.unlocalizedName + ".name" ); - if ( s.equals( this.unlocalizedName + ".name" ) ) + if( s.equals( this.unlocalizedName + ".name" ) ) return StatCollector.translateToLocal( this.unlocalizedName ); return s; } @Override - public int compareTo(ClientDCInternalInv o) + public int compareTo( ClientDCInternalInv o ) { return ItemSorters.compareLong( this.sortBy, o.sortBy ); } - } \ No newline at end of file diff --git a/src/main/java/appeng/client/me/InternalSlotME.java b/src/main/java/appeng/client/me/InternalSlotME.java index 2b9a07c11..5c91b6c7c 100644 --- a/src/main/java/appeng/client/me/InternalSlotME.java +++ b/src/main/java/appeng/client/me/InternalSlotME.java @@ -18,20 +18,22 @@ package appeng.client.me; + import net.minecraft.item.ItemStack; import appeng.api.storage.data.IAEItemStack; + public class InternalSlotME { - private final ItemRepo repo; - public final int offset; public final int xPos; public final int yPos; + private final ItemRepo repo; - public InternalSlotME(ItemRepo def, int offset, int displayX, int displayY) { + public InternalSlotME( ItemRepo def, int offset, int displayX, int displayY ) + { this.repo = def; this.offset = offset; this.xPos = displayX; diff --git a/src/main/java/appeng/client/me/ItemRepo.java b/src/main/java/appeng/client/me/ItemRepo.java index 10067a911..f1e4bee76 100644 --- a/src/main/java/appeng/client/me/ItemRepo.java +++ b/src/main/java/appeng/client/me/ItemRepo.java @@ -18,6 +18,7 @@ package appeng.client.me; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; @@ -44,6 +45,7 @@ import appeng.util.ItemSorters; import appeng.util.Platform; import appeng.util.prioitylist.IPartitionList; + public class ItemRepo { @@ -56,42 +58,45 @@ public class ItemRepo public int rowSize = 9; public String searchString = ""; + IPartitionList myPartitionList; private String innerSearch = ""; + private String NEIWord = null; + private boolean hasPower; - public ItemRepo(IScrollSource src, ISortSource sortSrc) + public ItemRepo( IScrollSource src, ISortSource sortSrc ) { this.src = src; this.sortSrc = sortSrc; } - public IAEItemStack getReferenceItem(int idx) + public IAEItemStack getReferenceItem( int idx ) { idx += this.src.getCurrentScroll() * this.rowSize; - if ( idx >= this.view.size() ) + if( idx >= this.view.size() ) return null; return this.view.get( idx ); } - public ItemStack getItem(int idx) + public ItemStack getItem( int idx ) { idx += this.src.getCurrentScroll() * this.rowSize; - if ( idx >= this.dsp.size() ) + if( idx >= this.dsp.size() ) return null; return this.dsp.get( idx ); } - void setSearch(String search) + void setSearch( String search ) { this.searchString = search == null ? "" : search; } - public void postUpdate(IAEItemStack is) + public void postUpdate( IAEItemStack is ) { IAEItemStack st = this.list.findPrecise( is ); - if ( st != null ) + if( st != null ) { st.reset(); st.add( is ); @@ -100,40 +105,12 @@ public class ItemRepo this.list.add( is ); } - IPartitionList myPartitionList; - - public void setViewCell(ItemStack[] list) + public void setViewCell( ItemStack[] list ) { this.myPartitionList = ItemViewCell.createFilter( list ); this.updateView(); } - private String NEIWord = null; - - private void updateNEI(String filter) - { - try - { - if ( this.NEIWord == null || !this.NEIWord.equals( filter ) ) - { - Class c = ReflectionHelper.getClass( this.getClass().getClassLoader(), "codechicken.nei.LayoutManager" ); - Field fldSearchField = c.getField( "searchField" ); - Object searchField = fldSearchField.get( c ); - - Method a = searchField.getClass().getMethod( "setText", String.class ); - Method b = searchField.getClass().getMethod( "onTextChange", String.class ); - - this.NEIWord = filter; - a.invoke( searchField, filter ); - b.invoke( searchField, "" ); - } - } - catch (Throwable ignore) - { - - } - } - public void updateView() { this.view.clear(); @@ -144,7 +121,7 @@ public class ItemRepo Enum viewMode = this.sortSrc.getSortDisplay(); Enum searchMode = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - if ( searchMode == SearchBoxMode.NEI_AUTOSEARCH || searchMode == SearchBoxMode.NEI_MANUAL_SEARCH ) + if( searchMode == SearchBoxMode.NEI_AUTOSEARCH || searchMode == SearchBoxMode.NEI_MANUAL_SEARCH ) this.updateNEI( this.searchString ); this.innerSearch = this.searchString; @@ -152,7 +129,7 @@ public class ItemRepo // boolean terminalSearchMods = Configuration.INSTANCE.settings.getSetting( Settings.SEARCH_MODS ) != YesNo.NO; boolean searchMod = false; - if ( this.innerSearch.startsWith( "@" ) ) + if( this.innerSearch.startsWith( "@" ) ) { searchMod = true; this.innerSearch = this.innerSearch.substring( 1 ); @@ -163,52 +140,52 @@ public class ItemRepo { m = Pattern.compile( this.innerSearch.toLowerCase(), Pattern.CASE_INSENSITIVE ); } - catch (Throwable ignore) + catch( Throwable ignore ) { try { m = Pattern.compile( Pattern.quote( this.innerSearch.toLowerCase() ), Pattern.CASE_INSENSITIVE ); } - catch (Throwable __) + catch( Throwable __ ) { return; } } boolean notDone = false; - for (IAEItemStack is : this.list) + for( IAEItemStack is : this.list ) { - if ( this.myPartitionList != null ) + if( this.myPartitionList != null ) { - if ( !this.myPartitionList.isListed( is ) ) + if( !this.myPartitionList.isListed( is ) ) continue; } - if ( viewMode == ViewItems.CRAFTABLE && !is.isCraftable() ) + if( viewMode == ViewItems.CRAFTABLE && !is.isCraftable() ) continue; - if ( viewMode == ViewItems.CRAFTABLE ) + if( viewMode == ViewItems.CRAFTABLE ) { is = is.copy(); is.setStackSize( 0 ); } - if ( viewMode == ViewItems.STORED && is.getStackSize() == 0 ) + if( viewMode == ViewItems.STORED && is.getStackSize() == 0 ) continue; String dspName = searchMod ? Platform.getModId( is ) : Platform.getItemDisplayName( is ); notDone = true; - if ( m.matcher( dspName.toLowerCase() ).find() ) + if( m.matcher( dspName.toLowerCase() ).find() ) { this.view.add( is ); notDone = false; } - if ( terminalSearchToolTips && notDone ) + if( terminalSearchToolTips && notDone ) { - for (Object lp : Platform.getTooltip( is )) - if ( lp instanceof String && m.matcher( (String) lp ).find() ) + for( Object lp : Platform.getTooltip( is ) ) + if( lp instanceof String && m.matcher( (String) lp ).find() ) { this.view.add( is ); notDone = false; @@ -228,19 +205,43 @@ public class ItemRepo ItemSorters.Direction = (appeng.api.config.SortDir) SortDir; ItemSorters.init(); - if ( SortBy == SortOrder.MOD ) + if( SortBy == SortOrder.MOD ) Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_MOD ); - else if ( SortBy == SortOrder.AMOUNT ) + else if( SortBy == SortOrder.AMOUNT ) Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_SIZE ); - else if ( SortBy == SortOrder.INVTWEAKS ) + else if( SortBy == SortOrder.INVTWEAKS ) Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_INV_TWEAKS ); else Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_NAME ); - for (IAEItemStack is : this.view) + for( IAEItemStack is : this.view ) this.dsp.add( is.getItemStack() ); } + private void updateNEI( String filter ) + { + try + { + if( this.NEIWord == null || !this.NEIWord.equals( filter ) ) + { + Class c = ReflectionHelper.getClass( this.getClass().getClassLoader(), "codechicken.nei.LayoutManager" ); + Field fldSearchField = c.getField( "searchField" ); + Object searchField = fldSearchField.get( c ); + + Method a = searchField.getClass().getMethod( "setText", String.class ); + Method b = searchField.getClass().getMethod( "onTextChange", String.class ); + + this.NEIWord = filter; + a.invoke( searchField, filter ); + b.invoke( searchField, "" ); + } + } + catch( Throwable ignore ) + { + + } + } + public int size() { return this.view.size(); @@ -251,16 +252,13 @@ public class ItemRepo this.list.resetStatus(); } - private boolean hasPower; - public boolean hasPower() { return this.hasPower; } - public void setPower(boolean hasPower) + public void setPower( boolean hasPower ) { this.hasPower = hasPower; } - } diff --git a/src/main/java/appeng/client/me/SlotDisconnected.java b/src/main/java/appeng/client/me/SlotDisconnected.java index 7c558a60f..e63ef1be8 100644 --- a/src/main/java/appeng/client/me/SlotDisconnected.java +++ b/src/main/java/appeng/client/me/SlotDisconnected.java @@ -18,6 +18,7 @@ package appeng.client.me; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -26,27 +27,47 @@ import appeng.container.slot.AppEngSlot; import appeng.items.misc.ItemEncodedPattern; import appeng.util.Platform; + public class SlotDisconnected extends AppEngSlot { public final ClientDCInternalInv mySlot; - public SlotDisconnected(ClientDCInternalInv me, int which, int x, int y) { + public SlotDisconnected( ClientDCInternalInv me, int which, int x, int y ) + { super( me.inv, which, x, y ); this.mySlot = me; } + @Override + public boolean isItemValid( ItemStack par1ItemStack ) + { + return false; + } + + @Override + public void putStack( ItemStack par1ItemStack ) + { + + } + + @Override + public boolean canTakeStack( EntityPlayer par1EntityPlayer ) + { + return false; + } + @Override public ItemStack getDisplayStack() { - if ( Platform.isClient() ) + if( Platform.isClient() ) { ItemStack is = super.getStack(); - if ( is != null && is.getItem() instanceof ItemEncodedPattern ) + if( is != null && is.getItem() instanceof ItemEncodedPattern ) { ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); ItemStack out = iep.getOutput( is ); - if ( out != null ) + if( out != null ) return out; } } @@ -54,21 +75,8 @@ public class SlotDisconnected extends AppEngSlot } @Override - public boolean canTakeStack(EntityPlayer par1EntityPlayer) + public void onPickupFromSlot( EntityPlayer par1EntityPlayer, ItemStack par2ItemStack ) { - return false; - } - - @Override - public ItemStack decrStackSize(int par1) - { - return null; - } - - @Override - public void putStack(ItemStack par1ItemStack) - { - } @Override @@ -77,12 +85,6 @@ public class SlotDisconnected extends AppEngSlot return this.getStack() != null; } - @Override - public boolean isItemValid(ItemStack par1ItemStack) - { - return false; - } - @Override public int getSlotStackLimit() { @@ -90,14 +92,14 @@ public class SlotDisconnected extends AppEngSlot } @Override - public boolean isSlotInInventory(IInventory par1iInventory, int par2) + public ItemStack decrStackSize( int par1 ) { - return false; + return null; } @Override - public void onPickupFromSlot(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack) + public boolean isSlotInInventory( IInventory par1iInventory, int par2 ) { + return false; } - } diff --git a/src/main/java/appeng/client/me/SlotME.java b/src/main/java/appeng/client/me/SlotME.java index accd4ef7e..c8d27945e 100644 --- a/src/main/java/appeng/client/me/SlotME.java +++ b/src/main/java/appeng/client/me/SlotME.java @@ -18,6 +18,7 @@ package appeng.client.me; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; @@ -25,61 +26,56 @@ import net.minecraft.item.ItemStack; import appeng.api.storage.data.IAEItemStack; + public class SlotME extends Slot { public final InternalSlotME mySlot; - public SlotME(InternalSlotME me) { + public SlotME( InternalSlotME me ) + { super( null, 0, me.xPos, me.yPos ); this.mySlot = me; } - @Override - public ItemStack getStack() - { - if ( this.mySlot.hasPower() ) - return this.mySlot.getStack(); - return null; - } - public IAEItemStack getAEStack() { - if ( this.mySlot.hasPower() ) + if( this.mySlot.hasPower() ) return this.mySlot.getAEStack(); return null; } @Override - public boolean canTakeStack(EntityPlayer par1EntityPlayer) + public void onPickupFromSlot( EntityPlayer par1EntityPlayer, ItemStack par2ItemStack ) + { + } + + @Override + public boolean isItemValid( ItemStack par1ItemStack ) { return false; } @Override - public ItemStack decrStackSize(int par1) + public ItemStack getStack() { + if( this.mySlot.hasPower() ) + return this.mySlot.getStack(); return null; } - @Override - public void putStack(ItemStack par1ItemStack) - { - - } - @Override public boolean getHasStack() { - if ( this.mySlot.hasPower() ) + if( this.mySlot.hasPower() ) return this.getStack() != null; return false; } @Override - public boolean isItemValid(ItemStack par1ItemStack) + public void putStack( ItemStack par1ItemStack ) { - return false; + } @Override @@ -89,14 +85,20 @@ public class SlotME extends Slot } @Override - public boolean isSlotInInventory(IInventory par1iInventory, int par2) + public ItemStack decrStackSize( int par1 ) + { + return null; + } + + @Override + public boolean isSlotInInventory( IInventory par1iInventory, int par2 ) { return false; } @Override - public void onPickupFromSlot(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack) + public boolean canTakeStack( EntityPlayer par1EntityPlayer ) { + return false; } - } diff --git a/src/main/java/appeng/client/render/AppEngRenderItem.java b/src/main/java/appeng/client/render/AppEngRenderItem.java index d4900da1c..fabd382ee 100644 --- a/src/main/java/appeng/client/render/AppEngRenderItem.java +++ b/src/main/java/appeng/client/render/AppEngRenderItem.java @@ -109,6 +109,17 @@ public class AppEngRenderItem extends RenderItem } } + private void renderQuad( Tessellator par1Tessellator, int par2, int par3, int par4, int par5, int par6 ) + { + par1Tessellator.startDrawingQuads(); + par1Tessellator.setColorOpaque_I( par6 ); + par1Tessellator.addVertex( par2, par3, 0.0D ); + par1Tessellator.addVertex( par2, par3 + par5, 0.0D ); + par1Tessellator.addVertex( par2 + par4, par3 + par5, 0.0D ); + par1Tessellator.addVertex( par2 + par4, par3, 0.0D ); + par1Tessellator.draw(); + } + private String getToBeRenderedStackSize( long originalSize ) { if( AEConfig.instance.useTerminalUseLargeFont() ) @@ -120,15 +131,4 @@ public class AppEngRenderItem extends RenderItem return NUMBER_CONVERTER.toHumanReadableForm( originalSize ); } } - - private void renderQuad( Tessellator par1Tessellator, int par2, int par3, int par4, int par5, int par6 ) - { - par1Tessellator.startDrawingQuads(); - par1Tessellator.setColorOpaque_I( par6 ); - par1Tessellator.addVertex( par2, par3, 0.0D ); - par1Tessellator.addVertex( par2, par3 + par5, 0.0D ); - par1Tessellator.addVertex( par2 + par4, par3 + par5, 0.0D ); - par1Tessellator.addVertex( par2 + par4, par3, 0.0D ); - par1Tessellator.draw(); - } } diff --git a/src/main/java/appeng/client/render/BaseBlockRender.java b/src/main/java/appeng/client/render/BaseBlockRender.java index f411fe770..5e7cab369 100644 --- a/src/main/java/appeng/client/render/BaseBlockRender.java +++ b/src/main/java/appeng/client/render/BaseBlockRender.java @@ -21,7 +21,6 @@ package appeng.client.render; import java.nio.FloatBuffer; import java.util.EnumSet; - import javax.annotation.Nullable; import org.lwjgl.BufferUtils; @@ -287,9 +286,9 @@ public class BaseBlockRender Tessellator tess = Tessellator.instance; BlockRenderInfo info = block.getRendererInstance(); - if ( info.isValid() ) + if( info.isValid() ) { - if ( block.hasSubtypes() ) + if( block.hasSubtypes() ) block.setRenderStateByMeta( item.getItemDamage() ); renderer.uvRotateBottom = info.getTexture( ForgeDirection.DOWN ).setFlip( getOrientation( ForgeDirection.DOWN, ForgeDirection.SOUTH, ForgeDirection.UP ) ); @@ -304,7 +303,7 @@ public class BaseBlockRender this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), block, item, tess, 0xffffff, renderer ); - if ( block.hasSubtypes() ) + if( block.hasSubtypes() ) info.setTemporaryRenderIcon( null ); renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; @@ -312,7 +311,7 @@ public class BaseBlockRender static public int getOrientation( ForgeDirection in, ForgeDirection forward, ForgeDirection up ) { - if ( in == null || in == ForgeDirection.UNKNOWN // 1 + if( in == null || in == ForgeDirection.UNKNOWN // 1 || forward == null || forward == ForgeDirection.UNKNOWN // 2 || up == null || up == ForgeDirection.UNKNOWN ) return 0; @@ -326,14 +325,14 @@ public class BaseBlockRender public void renderInvBlock( EnumSet sides, AEBaseBlock block, ItemStack item, Tessellator tess, int color, RenderBlocks renderer ) { - if ( Platform.isDrawing( tess ) ) + if( Platform.isDrawing( tess ) ) tess.draw(); int meta = 0; - if ( block != null && block.hasSubtypes() && item != null ) + if( block != null && block.hasSubtypes() && item != null ) meta = item.getItemDamage(); - if ( sides.contains( ForgeDirection.DOWN ) ) + if( sides.contains( ForgeDirection.DOWN ) ) { tess.startDrawingQuads(); tess.setNormal( 0.0F, -1.0F, 0.0F ); @@ -342,7 +341,7 @@ public class BaseBlockRender tess.draw(); } - if ( sides.contains( ForgeDirection.UP ) ) + if( sides.contains( ForgeDirection.UP ) ) { tess.startDrawingQuads(); tess.setNormal( 0.0F, 1.0F, 0.0F ); @@ -351,7 +350,7 @@ public class BaseBlockRender tess.draw(); } - if ( sides.contains( ForgeDirection.NORTH ) ) + if( sides.contains( ForgeDirection.NORTH ) ) { tess.startDrawingQuads(); tess.setNormal( 0.0F, 0.0F, -1.0F ); @@ -360,7 +359,7 @@ public class BaseBlockRender tess.draw(); } - if ( sides.contains( ForgeDirection.SOUTH ) ) + if( sides.contains( ForgeDirection.SOUTH ) ) { tess.startDrawingQuads(); tess.setNormal( 0.0F, 0.0F, 1.0F ); @@ -369,7 +368,7 @@ public class BaseBlockRender tess.draw(); } - if ( sides.contains( ForgeDirection.WEST ) ) + if( sides.contains( ForgeDirection.WEST ) ) { tess.startDrawingQuads(); tess.setNormal( -1.0F, 0.0F, 0.0F ); @@ -378,7 +377,7 @@ public class BaseBlockRender tess.draw(); } - if ( sides.contains( ForgeDirection.EAST ) ) + if( sides.contains( ForgeDirection.EAST ) ) { tess.startDrawingQuads(); tess.setNormal( 1.0F, 0.0F, 0.0F ); @@ -390,8 +389,8 @@ public class BaseBlockRender public IIcon firstNotNull( IIcon... s ) { - for ( IIcon o : s ) - if ( o != null ) + for( IIcon o : s ) + if( o != null ) return o; return ExtraBlockTextures.getMissing(); } @@ -413,7 +412,7 @@ public class BaseBlockRender BlockRenderInfo info = block.getRendererInstance(); IOrientable te = this.getOrientable( block, world, x, y, z ); - if ( te != null ) + if( te != null ) { forward = te.getForward(); up = te.getUp(); @@ -437,9 +436,9 @@ public class BaseBlockRender @Nullable public IOrientable getOrientable( AEBaseBlock block, IBlockAccess w, int x, int y, int z ) { - if ( block.hasBlockTileEntity() ) + if( block.hasBlockTileEntity() ) return (AEBaseTile) block.getTileEntity( w, x, y, z ); - else if ( block instanceof IOrientableBlock ) + else if( block instanceof IOrientableBlock ) return ( (IOrientableBlock) block ).getOrientable( w, x, y, z ); return null; } @@ -472,19 +471,19 @@ public class BaseBlockRender double bY = maxX * x.offsetY + maxY * y.offsetY + maxZ * z.offsetY; double bZ = maxX * x.offsetZ + maxY * y.offsetZ + maxZ * z.offsetZ; - if ( x.offsetX + y.offsetX + z.offsetX < 0 ) + if( x.offsetX + y.offsetX + z.offsetX < 0 ) { aX += 1; bX += 1; } - if ( x.offsetY + y.offsetY + z.offsetY < 0 ) + if( x.offsetY + y.offsetY + z.offsetY < 0 ) { aY += 1; bY += 1; } - if ( x.offsetZ + y.offsetZ + z.offsetZ < 0 ) + if( x.offsetZ + y.offsetZ + z.offsetZ < 0 ) { aZ += 1; bZ += 1; @@ -514,7 +513,7 @@ public class BaseBlockRender double layerBZ = 0.0; boolean flip = false; - switch ( orientation ) + switch( orientation ) { case NORTH: @@ -594,7 +593,7 @@ public class BaseBlockRender @SideOnly( Side.CLIENT ) private void renderFace( Tessellator tess, double offsetX, double offsetY, double offsetZ, double ax, double ay, double az, double bx, double by, double bz, double ua, double ub, double va, double vb, IIcon ico, boolean flip ) { - if ( flip ) + if( flip ) { tess.addVertexWithUV( offsetX + ax * ua + bx * va, offsetY + ay * ua + by * va, offsetZ + az * ua + bz * va, ico.getInterpolatedU( ua * 16.0 ), ico.getInterpolatedV( va * 16.0 ) ); tess.addVertexWithUV( offsetX + ax * ua + bx * vb, offsetY + ay * ua + by * vb, offsetZ + az * ua + bz * vb, ico.getInterpolatedU( ua * 16.0 ), ico.getInterpolatedV( vb * 16.0 ) ); @@ -613,7 +612,7 @@ public class BaseBlockRender @SideOnly( Side.CLIENT ) protected void renderFace( int x, int y, int z, Block block, IIcon ico, RenderBlocks renderer, ForgeDirection orientation ) { - switch ( orientation ) + switch( orientation ) { case NORTH: renderer.renderFaceZNeg( block, x, y, z, ico ); @@ -663,10 +662,10 @@ public class BaseBlockRender private double mapFaceUV( int offset, int uv ) { - if ( offset == 0 ) + if( offset == 0 ) return 0; - if ( offset > 0 ) + if( offset > 0 ) return uv / 16.0; return ( 16.0 - uv ) / 16.0; @@ -684,7 +683,7 @@ public class BaseBlockRender Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.locationBlocksTexture ); RenderHelper.disableStandardItemLighting(); - if ( Minecraft.isAmbientOcclusionEnabled() ) + if( Minecraft.isAmbientOcclusionEnabled() ) GL11.glShadeModel( GL11.GL_SMOOTH ); else GL11.glShadeModel( GL11.GL_FLAT ); @@ -707,12 +706,12 @@ public class BaseBlockRender protected void applyTESRRotation( double x, double y, double z, ForgeDirection forward, ForgeDirection up ) { - if ( forward != null && up != null ) + if( forward != null && up != null ) { - if ( forward == ForgeDirection.UNKNOWN ) + if( forward == ForgeDirection.UNKNOWN ) forward = ForgeDirection.SOUTH; - if ( up == ForgeDirection.UNKNOWN ) + if( up == ForgeDirection.UNKNOWN ) up = ForgeDirection.UP; ForgeDirection west = Platform.crossProduct( forward, up ); @@ -749,7 +748,7 @@ public class BaseBlockRender public void doRenderItem( ItemStack itemstack, TileEntity par1EntityItemFrame ) { - if ( itemstack != null ) + if( itemstack != null ) { EntityItem entityitem = new EntityItem( par1EntityItemFrame.getWorldObj(), 0.0D, 0.0D, 0.0D, itemstack ); entityitem.getEntityItem().stackSize = 1; diff --git a/src/main/java/appeng/client/render/BlockRenderInfo.java b/src/main/java/appeng/client/render/BlockRenderInfo.java index 481d994d5..b9fb62b7c 100644 --- a/src/main/java/appeng/client/render/BlockRenderInfo.java +++ b/src/main/java/appeng/client/render/BlockRenderInfo.java @@ -18,29 +18,25 @@ package appeng.client.render; + import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import appeng.client.texture.FlippableIcon; import appeng.client.texture.TmpFlippableIcon; + public class BlockRenderInfo { - public BlockRenderInfo(BaseBlockRender inst) { - this.rendererInstance = inst; - } - final public BaseBlockRender rendererInstance; - - private boolean useTmp = false; private final TmpFlippableIcon tmpTopIcon = new TmpFlippableIcon(); private final TmpFlippableIcon tmpBottomIcon = new TmpFlippableIcon(); private final TmpFlippableIcon tmpSouthIcon = new TmpFlippableIcon(); private final TmpFlippableIcon tmpNorthIcon = new TmpFlippableIcon(); private final TmpFlippableIcon tmpEastIcon = new TmpFlippableIcon(); private final TmpFlippableIcon tmpWestIcon = new TmpFlippableIcon(); - + private boolean useTmp = false; private FlippableIcon topIcon = null; private FlippableIcon bottomIcon = null; private FlippableIcon southIcon = null; @@ -48,7 +44,12 @@ public class BlockRenderInfo private FlippableIcon eastIcon = null; private FlippableIcon westIcon = null; - public void updateIcons(FlippableIcon Bottom, FlippableIcon Top, FlippableIcon North, FlippableIcon South, FlippableIcon East, FlippableIcon West) + public BlockRenderInfo( BaseBlockRender inst ) + { + this.rendererInstance = inst; + } + + public void updateIcons( FlippableIcon Bottom, FlippableIcon Top, FlippableIcon North, FlippableIcon South, FlippableIcon East, FlippableIcon West ) { this.topIcon = Top; this.bottomIcon = Bottom; @@ -56,12 +57,11 @@ public class BlockRenderInfo this.northIcon = North; this.eastIcon = East; this.westIcon = West; - } - public void setTemporaryRenderIcon(IIcon IIcon) + public void setTemporaryRenderIcon( IIcon IIcon ) { - if ( IIcon == null ) + if( IIcon == null ) this.useTmp = false; else { @@ -75,7 +75,7 @@ public class BlockRenderInfo } } - public void setTemporaryRenderIcons(IIcon nTopIcon, IIcon nBottomIcon, IIcon nSouthIcon, IIcon nNorthIcon, IIcon nEastIcon, IIcon nWestIcon) + public void setTemporaryRenderIcons( IIcon nTopIcon, IIcon nBottomIcon, IIcon nSouthIcon, IIcon nNorthIcon, IIcon nEastIcon, IIcon nWestIcon ) { this.tmpTopIcon.setOriginal( nTopIcon == null ? this.getTexture( ForgeDirection.UP ) : nTopIcon ); this.tmpBottomIcon.setOriginal( nBottomIcon == null ? this.getTexture( ForgeDirection.DOWN ) : nBottomIcon ); @@ -86,45 +86,45 @@ public class BlockRenderInfo this.useTmp = true; } - public FlippableIcon getTexture(ForgeDirection dir) + public FlippableIcon getTexture( ForgeDirection dir ) { - if ( this.useTmp ) + if( this.useTmp ) { - switch (dir) + switch( dir ) { - case DOWN: - return this.tmpBottomIcon; - case UP: - return this.tmpTopIcon; - case NORTH: - return this.tmpNorthIcon; - case SOUTH: - return this.tmpSouthIcon; - case EAST: - return this.tmpEastIcon; - case WEST: - return this.tmpWestIcon; - default: - break; + case DOWN: + return this.tmpBottomIcon; + case UP: + return this.tmpTopIcon; + case NORTH: + return this.tmpNorthIcon; + case SOUTH: + return this.tmpSouthIcon; + case EAST: + return this.tmpEastIcon; + case WEST: + return this.tmpWestIcon; + default: + break; } } - switch (dir) + switch( dir ) { - case DOWN: - return this.bottomIcon; - case UP: - return this.topIcon; - case NORTH: - return this.northIcon; - case SOUTH: - return this.southIcon; - case EAST: - return this.eastIcon; - case WEST: - return this.westIcon; - default: - break; + case DOWN: + return this.bottomIcon; + case UP: + return this.topIcon; + case NORTH: + return this.northIcon; + case SOUTH: + return this.southIcon; + case EAST: + return this.eastIcon; + case WEST: + return this.westIcon; + default: + break; } return this.topIcon; @@ -134,5 +134,4 @@ public class BlockRenderInfo { return this.topIcon != null && this.bottomIcon != null && this.southIcon != null && this.northIcon != null && this.eastIcon != null && this.westIcon != null; } - } diff --git a/src/main/java/appeng/client/render/BusRenderHelper.java b/src/main/java/appeng/client/render/BusRenderHelper.java index f787d947a..6282331d0 100644 --- a/src/main/java/appeng/client/render/BusRenderHelper.java +++ b/src/main/java/appeng/client/render/BusRenderHelper.java @@ -89,7 +89,7 @@ public final class BusRenderHelper implements IPartRenderHelper this.az = ForgeDirection.SOUTH; this.ay = ForgeDirection.UP; this.color = HEX_WHITE; - this.maybeBlock = AEApi.instance().definitions().blocks().multiPart().maybeBlock(); + this.maybeBlock = AEApi.instance().definitions().blocks().multiPart().maybeBlock(); this.maybeBaseBlock = this.maybeBlock.transform( new BaseBlockTransformFunction() ); } @@ -107,7 +107,7 @@ public final class BusRenderHelper implements IPartRenderHelper public double getBound( ForgeDirection side ) { - switch ( side ) + switch( side ) { default: case UNKNOWN: @@ -129,7 +129,7 @@ public final class BusRenderHelper implements IPartRenderHelper public void setRenderColor( int color ) { - for ( Block block : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) + for( Block block : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) { final BlockCableBus cableBus = (BlockCableBus) block; cableBus.setRenderColor( color ); @@ -150,7 +150,7 @@ public final class BusRenderHelper implements IPartRenderHelper public void setBounds( double[] bounds ) { - if ( bounds == null || bounds.length != 6 ) + if( bounds == null || bounds.length != 6 ) return; this.minX = bounds[0]; @@ -161,7 +161,6 @@ public final class BusRenderHelper implements IPartRenderHelper this.maxZ = bounds[5]; } - private static class BoundBoxCalculator implements IPartCollisionHelper { private final BusRenderHelper helper; @@ -183,7 +182,7 @@ public final class BusRenderHelper implements IPartRenderHelper @Override public void addBox( double minX, double minY, double minZ, double maxX, double maxY, double maxZ ) { - if ( this.started ) + if( this.started ) { this.minX = Math.min( this.minX, (float) minX ); this.minY = Math.min( this.minY, (float) minY ); @@ -227,17 +226,33 @@ public final class BusRenderHelper implements IPartRenderHelper { return false; } - } @Override + } + + + private static final class BaseBlockTransformFunction implements Function + { + @Nullable + @Override + public AEBaseBlock apply( Block input ) + { + if( input instanceof AEBaseBlock ) + { + return ( (AEBaseBlock) input ); + } + + return null; + } + } + + @Override public void renderForPass( int pass ) { this.renderingForPass = pass; } - - public boolean renderThis() { - if ( this.renderingForPass == this.currentPass || this.noAlphaPass ) + if( this.renderingForPass == this.currentPass || this.noAlphaPass ) { this.itemsRendered++; return true; @@ -259,7 +274,7 @@ public final class BusRenderHelper implements IPartRenderHelper { RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.renderer; - if ( sim != null && this.maybeBlock.isPresent() && rbw.similarLighting( this.maybeBlock.get(), rbw.blockAccess, x, y, z, sim ) ) + if( sim != null && this.maybeBlock.isPresent() && rbw.similarLighting( this.maybeBlock.get(), rbw.blockAccess, x, y, z, sim ) ) { rbw.populate( sim ); rbw.faces = EnumSet.allOf( ForgeDirection.class ); @@ -276,7 +291,7 @@ public final class BusRenderHelper implements IPartRenderHelper rbw.faces.clear(); this.bbc.started = false; - if ( p == null ) + if( p == null ) { this.bbc.minX = this.bbc.minY = this.bbc.minZ = 0; this.bbc.maxX = this.bbc.maxY = this.bbc.maxZ = 16; @@ -285,18 +300,18 @@ public final class BusRenderHelper implements IPartRenderHelper { p.getBoxes( this.bbc ); - if ( this.bbc.minX < 1 ) + if( this.bbc.minX < 1 ) this.bbc.minX = 1; - if ( this.bbc.minY < 1 ) + if( this.bbc.minY < 1 ) this.bbc.minY = 1; - if ( this.bbc.minZ < 1 ) + if( this.bbc.minZ < 1 ) this.bbc.minZ = 1; - if ( this.bbc.maxX > 15 ) + if( this.bbc.maxX > 15 ) this.bbc.maxX = 15; - if ( this.bbc.maxY > 15 ) + if( this.bbc.maxY > 15 ) this.bbc.maxY = 15; - if ( this.bbc.maxZ > 15 ) + if( this.bbc.maxZ > 15 ) this.bbc.maxZ = 15; } @@ -304,7 +319,7 @@ public final class BusRenderHelper implements IPartRenderHelper this.bbr.renderBlockBounds( rbw, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az ); - for ( Block block : this.maybeBlock.asSet() ) + for( Block block : this.maybeBlock.asSet() ) { rbw.renderStandardBlock( block, x, y, z ); } @@ -338,7 +353,7 @@ public final class BusRenderHelper implements IPartRenderHelper @Override public void setTexture( IIcon ico ) { - for ( AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) + for( AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) { baseBlock.getRendererInstance().setTemporaryRenderIcon( ico ); } @@ -356,7 +371,7 @@ public final class BusRenderHelper implements IPartRenderHelper list[4] = West; list[5] = East; - for ( AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) + for( AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) { baseBlock.getRendererInstance().setTemporaryRenderIcons( list[this.mapRotation( ForgeDirection.UP ).ordinal()], list[this.mapRotation( ForgeDirection.DOWN ).ordinal()], list[this.mapRotation( ForgeDirection.SOUTH ).ordinal()], list[this.mapRotation( ForgeDirection.NORTH ).ordinal()], list[this.mapRotation( ForgeDirection.EAST ).ordinal()], list[this.mapRotation( ForgeDirection.WEST ).ordinal()] ); } @@ -368,30 +383,30 @@ public final class BusRenderHelper implements IPartRenderHelper ForgeDirection up = this.ay; ForgeDirection west = ForgeDirection.UNKNOWN; - if ( forward == null || up == null ) + if( forward == null || up == null ) return dir; int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - for ( ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS ) - if ( dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z ) + for( ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS ) + if( dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z ) west = dx; - if ( dir == forward ) + if( dir == forward ) return ForgeDirection.SOUTH; - if ( dir == forward.getOpposite() ) + if( dir == forward.getOpposite() ) return ForgeDirection.NORTH; - if ( dir == up ) + if( dir == up ) return ForgeDirection.UP; - if ( dir == up.getOpposite() ) + if( dir == up.getOpposite() ) return ForgeDirection.DOWN; - if ( dir == west ) + if( dir == west ) return ForgeDirection.WEST; - if ( dir == west.getOpposite() ) + if( dir == west.getOpposite() ) return ForgeDirection.EAST; return ForgeDirection.UNKNOWN; @@ -402,7 +417,7 @@ public final class BusRenderHelper implements IPartRenderHelper { renderer.setRenderBounds( this.minX / 16.0, this.minY / 16.0, this.minZ / 16.0, this.maxX / 16.0, this.maxY / 16.0, this.maxZ / 16.0 ); - for ( AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) + for( AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) { this.bbr.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), baseBlock, null, Tessellator.instance, this.color, renderer ); } @@ -414,7 +429,7 @@ public final class BusRenderHelper implements IPartRenderHelper renderer.setRenderBounds( this.minX / 16.0, this.minY / 16.0, this.minZ / 16.0, this.maxX / 16.0, this.maxY / 16.0, this.maxZ / 16.0 ); this.setTexture( IIcon ); - for ( AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) + for( AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) { this.bbr.renderInvBlock( EnumSet.of( face ), baseBlock, null, Tessellator.instance, this.color, renderer ); } @@ -423,10 +438,10 @@ public final class BusRenderHelper implements IPartRenderHelper @Override public void renderBlock( int x, int y, int z, RenderBlocks renderer ) { - if ( !this.renderThis() ) + if( !this.renderThis() ) return; - for ( Block multiPart : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) + for( Block multiPart : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) { final AEBaseBlock block = (AEBaseBlock) multiPart; @@ -452,7 +467,7 @@ public final class BusRenderHelper implements IPartRenderHelper @Override public Block getBlock() { - for ( Block block : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) + for( Block block : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) { return block; } @@ -474,10 +489,10 @@ public final class BusRenderHelper implements IPartRenderHelper @Override public void renderBlockCurrentBounds( int x, int y, int z, RenderBlocks renderer ) { - if ( !this.renderThis() ) + if( !this.renderThis() ) return; - for ( Block block : this.maybeBlock.asSet() ) + for( Block block : this.maybeBlock.asSet() ) { renderer.renderStandardBlock( block, x, y, z ); } @@ -486,10 +501,10 @@ public final class BusRenderHelper implements IPartRenderHelper @Override public void renderFaceCutout( int x, int y, int z, IIcon ico, ForgeDirection face, float edgeThickness, RenderBlocks renderer ) { - if ( !this.renderThis() ) + if( !this.renderThis() ) return; - switch ( face ) + switch( face ) { case DOWN: face = this.ay.getOpposite(); @@ -515,7 +530,7 @@ public final class BusRenderHelper implements IPartRenderHelper break; } - for ( Block block : this.maybeBlock.asSet() ) + for( Block block : this.maybeBlock.asSet() ) { this.bbr.renderCutoutFace( block, ico, x, y, z, renderer, face, edgeThickness ); } @@ -524,11 +539,11 @@ public final class BusRenderHelper implements IPartRenderHelper @Override public void renderFace( int x, int y, int z, IIcon ico, ForgeDirection face, RenderBlocks renderer ) { - if ( !this.renderThis() ) + if( !this.renderThis() ) return; this.prepareBounds( renderer ); - switch ( face ) + switch( face ) { case DOWN: face = this.ay.getOpposite(); @@ -554,7 +569,7 @@ public final class BusRenderHelper implements IPartRenderHelper break; } - for ( Block block : this.maybeBlock.asSet() ) + for( Block block : this.maybeBlock.asSet() ) { this.bbr.renderFace( x, y, z, block, ico, renderer, face ); } @@ -577,19 +592,4 @@ public final class BusRenderHelper implements IPartRenderHelper { return this.az; } - - private static final class BaseBlockTransformFunction implements Function - { - @Nullable - @Override - public AEBaseBlock apply( Block input ) - { - if ( input instanceof AEBaseBlock ) - { - return ( (AEBaseBlock) input ); - } - - return null; - } - } } diff --git a/src/main/java/appeng/client/render/BusRenderer.java b/src/main/java/appeng/client/render/BusRenderer.java index 740be69f7..74c6e9615 100644 --- a/src/main/java/appeng/client/render/BusRenderer.java +++ b/src/main/java/appeng/client/render/BusRenderer.java @@ -18,6 +18,7 @@ package appeng.client.render; + import java.util.HashMap; import java.util.Map; @@ -42,46 +43,31 @@ import appeng.core.features.AEFeature; import appeng.facade.IFacadeItem; import appeng.util.Platform; -@SideOnly(Side.CLIENT) + +@SideOnly( Side.CLIENT ) public class BusRenderer implements IItemRenderer { public static final BusRenderer INSTANCE = new BusRenderer(); - - public final RenderBlocksWorkaround renderer = new RenderBlocksWorkaround(); private static final Map RENDER_PART = new HashMap(); - - public IPart getRenderer(ItemStack is, IPartItem c) - { - int id = (Item.getIdFromItem( is.getItem() ) << Platform.DEF_OFFSET) | is.getItemDamage(); - - IPart part = RENDER_PART.get( id ); - if ( part == null ) - { - part = c.createPartFromItemStack( is ); - if ( part != null ) - RENDER_PART.put( id, part ); - } - - return part; - } + public final RenderBlocksWorkaround renderer = new RenderBlocksWorkaround(); @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) + public boolean handleRenderType( ItemStack item, ItemRenderType type ) { return true; } @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) + public boolean shouldUseRenderHelper( ItemRenderType type, ItemStack item, ItemRendererHelper helper ) { return true; } @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) + public void renderItem( ItemRenderType type, ItemStack item, Object... data ) { - if ( item == null ) + if( item == null ) return; GL11.glPushMatrix(); @@ -90,8 +76,7 @@ public class BusRenderer implements IItemRenderer GL11.glEnable( GL11.GL_TEXTURE_2D ); GL11.glEnable( GL11.GL_LIGHTING ); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) && item.getItem() instanceof IAlphaPassItem - && ((IAlphaPassItem) item.getItem()).useAlphaPass( item ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) && item.getItem() instanceof IAlphaPassItem && ( (IAlphaPassItem) item.getItem() ).useAlphaPass( item ) ) { GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); @@ -105,19 +90,19 @@ public class BusRenderer implements IItemRenderer GL11.glDisable( GL11.GL_BLEND ); } - if ( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) + if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) { GL11.glTranslatef( -0.2f, -0.1f, -0.3f ); } - if ( type == ItemRenderType.ENTITY ) + if( type == ItemRenderType.ENTITY ) { GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); GL11.glScalef( 0.8f, 0.8f, 0.8f ); GL11.glTranslatef( -0.8f, -0.87f, -0.7f ); } - if ( type == ItemRenderType.INVENTORY ) + if( type == ItemRenderType.INVENTORY ) GL11.glTranslatef( 0.0f, -0.1f, 0.0f ); GL11.glTranslated( 0.2, 0.3, 0.1 ); @@ -138,29 +123,29 @@ public class BusRenderer implements IItemRenderer this.renderer.useInventoryTint = false; this.renderer.overrideBlockTexture = null; - if ( item.getItem() instanceof IFacadeItem ) + if( item.getItem() instanceof IFacadeItem ) { IFacadeItem fi = (IFacadeItem) item.getItem(); IFacadePart fp = fi.createPartFromItemStack( item, ForgeDirection.SOUTH ); - if ( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) + if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) { GL11.glRotatef( 160.0f, 0.0f, 1.0f, 0.0f ); GL11.glTranslated( -0.4, 0.1, -1.6 ); } - if ( fp != null ) + if( fp != null ) fp.renderInventory( BusRenderHelper.INSTANCE, this.renderer ); } else { IPart ip = this.getRenderer( item, (IPartItem) item.getItem() ); - if ( ip != null ) + if( ip != null ) { - if ( type == ItemRenderType.ENTITY ) + if( type == ItemRenderType.ENTITY ) { int depth = ip.cableConnectionRenderTo(); - GL11.glTranslatef( 0.0f, 0.0f, -0.04f * (8 - depth) - 0.06f ); + GL11.glTranslatef( 0.0f, 0.0f, -0.04f * ( 8 - depth ) - 0.06f ); } ip.renderInventory( BusRenderHelper.INSTANCE, this.renderer ); @@ -172,4 +157,19 @@ public class BusRenderer implements IItemRenderer GL11.glPopAttrib(); GL11.glPopMatrix(); } + + public IPart getRenderer( ItemStack is, IPartItem c ) + { + int id = ( Item.getIdFromItem( is.getItem() ) << Platform.DEF_OFFSET ) | is.getItemDamage(); + + IPart part = RENDER_PART.get( id ); + if( part == null ) + { + part = c.createPartFromItemStack( is ); + if( part != null ) + RENDER_PART.put( id, part ); + } + + return part; + } } diff --git a/src/main/java/appeng/client/render/CableRenderHelper.java b/src/main/java/appeng/client/render/CableRenderHelper.java index cec627144..3e23343f0 100644 --- a/src/main/java/appeng/client/render/CableRenderHelper.java +++ b/src/main/java/appeng/client/render/CableRenderHelper.java @@ -18,6 +18,7 @@ package appeng.client.render; + import java.util.ArrayList; import java.util.EnumSet; import java.util.List; @@ -33,6 +34,7 @@ import appeng.api.parts.IPart; import appeng.parts.BusCollisionHelper; import appeng.parts.CableBusContainer; + public class CableRenderHelper { @@ -43,70 +45,21 @@ public class CableRenderHelper return INSTANCE; } - private void setSide(ForgeDirection s) - { - ForgeDirection ax; - ForgeDirection ay; - ForgeDirection az; - - switch (s) - { - case DOWN: - ax = ForgeDirection.EAST; - ay = ForgeDirection.NORTH; - az = ForgeDirection.DOWN; - break; - case UP: - ax = ForgeDirection.EAST; - ay = ForgeDirection.SOUTH; - az = ForgeDirection.UP; - break; - case EAST: - ax = ForgeDirection.SOUTH; - ay = ForgeDirection.UP; - az = ForgeDirection.EAST; - break; - case WEST: - ax = ForgeDirection.NORTH; - ay = ForgeDirection.UP; - az = ForgeDirection.WEST; - break; - case NORTH: - ax = ForgeDirection.WEST; - ay = ForgeDirection.UP; - az = ForgeDirection.NORTH; - break; - case SOUTH: - ax = ForgeDirection.EAST; - ay = ForgeDirection.UP; - az = ForgeDirection.SOUTH; - break; - case UNKNOWN: - default: - ax = ForgeDirection.EAST; - ay = ForgeDirection.UP; - az = ForgeDirection.SOUTH; - break; - } - - BusRenderHelper.INSTANCE.setOrientation( ax, ay, az ); - } - - public void renderStatic(CableBusContainer cableBusContainer, IFacadeContainer iFacadeContainer) + public void renderStatic( CableBusContainer cableBusContainer, IFacadeContainer iFacadeContainer ) { TileEntity te = cableBusContainer.getTile(); RenderBlocksWorkaround renderer = BusRenderer.INSTANCE.renderer; - if ( renderer.overrideBlockTexture != null ) + if( renderer.overrideBlockTexture != null ) BusRenderHelper.INSTANCE.setPass( 0 ); - if ( renderer.blockAccess == null ) + if( renderer.blockAccess == null ) renderer.blockAccess = Minecraft.getMinecraft().theWorld; - for (ForgeDirection s : ForgeDirection.values()) + for( ForgeDirection s : ForgeDirection.values() ) { IPart part = cableBusContainer.getPart( s ); - if ( part != null ) + if( part != null ) { this.setSide( s ); renderer.renderAllFaces = true; @@ -122,16 +75,16 @@ public class CableRenderHelper } } - if ( !iFacadeContainer.isEmpty() ) + if( !iFacadeContainer.isEmpty() ) { /** * snag list of boxes... */ List boxes = new ArrayList(); - for (ForgeDirection s : ForgeDirection.values()) + for( ForgeDirection s : ForgeDirection.values() ) { IPart part = cableBusContainer.getPart( s ); - if ( part != null ) + if( part != null ) { this.setSide( s ); BusRenderHelper brh = BusRenderHelper.INSTANCE; @@ -144,7 +97,7 @@ public class CableRenderHelper double min = 2.0 / 16.0; double max = 14.0 / 16.0; - for (AxisAlignedBB bb : boxes) + for( AxisAlignedBB bb : boxes ) { int o = 0; o += bb.maxX > max ? 1 : 0; @@ -154,23 +107,23 @@ public class CableRenderHelper o += bb.minY < min ? 1 : 0; o += bb.minZ < min ? 1 : 0; - if ( o >= 2 ) + if( o >= 2 ) useThinFacades = true; } - for (ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) { IFacadePart fPart = iFacadeContainer.getFacade( s ); - if ( fPart != null ) + if( fPart != null ) { AxisAlignedBB b = null; fPart.setThinFacades( useThinFacades ); AxisAlignedBB pb = fPart.getPrimaryBox(); - for (AxisAlignedBB bb : boxes) + for( AxisAlignedBB bb : boxes ) { - if ( bb.intersectsWith( pb ) ) + if( bb.intersectsWith( pb ) ) { - if ( b == null ) + if( b == null ) b = bb; else { @@ -188,8 +141,7 @@ public class CableRenderHelper renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; this.setSide( s ); - fPart.renderStatic( te.xCoord, te.yCoord, te.zCoord, BusRenderHelper.INSTANCE, renderer, iFacadeContainer, b, - cableBusContainer.getPart( s ) == null ); + fPart.renderStatic( te.xCoord, te.yCoord, te.zCoord, BusRenderHelper.INSTANCE, renderer, iFacadeContainer, b, cableBusContainer.getPart( s ) == null ); } } @@ -200,55 +152,104 @@ public class CableRenderHelper } } - public void renderDynamic(CableBusContainer cableBusContainer, double x, double y, double z) + private void setSide( ForgeDirection s ) { - for (ForgeDirection s : ForgeDirection.values()) + ForgeDirection ax; + ForgeDirection ay; + ForgeDirection az; + + switch( s ) + { + case DOWN: + ax = ForgeDirection.EAST; + ay = ForgeDirection.NORTH; + az = ForgeDirection.DOWN; + break; + case UP: + ax = ForgeDirection.EAST; + ay = ForgeDirection.SOUTH; + az = ForgeDirection.UP; + break; + case EAST: + ax = ForgeDirection.SOUTH; + ay = ForgeDirection.UP; + az = ForgeDirection.EAST; + break; + case WEST: + ax = ForgeDirection.NORTH; + ay = ForgeDirection.UP; + az = ForgeDirection.WEST; + break; + case NORTH: + ax = ForgeDirection.WEST; + ay = ForgeDirection.UP; + az = ForgeDirection.NORTH; + break; + case SOUTH: + ax = ForgeDirection.EAST; + ay = ForgeDirection.UP; + az = ForgeDirection.SOUTH; + break; + case UNKNOWN: + default: + ax = ForgeDirection.EAST; + ay = ForgeDirection.UP; + az = ForgeDirection.SOUTH; + break; + } + + BusRenderHelper.INSTANCE.setOrientation( ax, ay, az ); + } + + public void renderDynamic( CableBusContainer cableBusContainer, double x, double y, double z ) + { + for( ForgeDirection s : ForgeDirection.values() ) { IPart part = cableBusContainer.getPart( s ); - if ( part != null ) + if( part != null ) { ForgeDirection ax; ForgeDirection ay; ForgeDirection az; - switch (s) + switch( s ) { - case DOWN: - ax = ForgeDirection.EAST; - ay = ForgeDirection.NORTH; - az = ForgeDirection.DOWN; - break; - case UP: - ax = ForgeDirection.EAST; - ay = ForgeDirection.SOUTH; - az = ForgeDirection.UP; - break; - case EAST: - ax = ForgeDirection.SOUTH; - ay = ForgeDirection.UP; - az = ForgeDirection.EAST; - break; - case WEST: - ax = ForgeDirection.NORTH; - ay = ForgeDirection.UP; - az = ForgeDirection.WEST; - break; - case NORTH: - ax = ForgeDirection.WEST; - ay = ForgeDirection.UP; - az = ForgeDirection.NORTH; - break; - case SOUTH: - ax = ForgeDirection.EAST; - ay = ForgeDirection.UP; - az = ForgeDirection.SOUTH; - break; - case UNKNOWN: - default: - ax = ForgeDirection.EAST; - ay = ForgeDirection.UP; - az = ForgeDirection.SOUTH; - break; + case DOWN: + ax = ForgeDirection.EAST; + ay = ForgeDirection.NORTH; + az = ForgeDirection.DOWN; + break; + case UP: + ax = ForgeDirection.EAST; + ay = ForgeDirection.SOUTH; + az = ForgeDirection.UP; + break; + case EAST: + ax = ForgeDirection.SOUTH; + ay = ForgeDirection.UP; + az = ForgeDirection.EAST; + break; + case WEST: + ax = ForgeDirection.NORTH; + ay = ForgeDirection.UP; + az = ForgeDirection.WEST; + break; + case NORTH: + ax = ForgeDirection.WEST; + ay = ForgeDirection.UP; + az = ForgeDirection.NORTH; + break; + case SOUTH: + ax = ForgeDirection.EAST; + ay = ForgeDirection.UP; + az = ForgeDirection.SOUTH; + break; + case UNKNOWN: + default: + ax = ForgeDirection.EAST; + ay = ForgeDirection.UP; + az = ForgeDirection.SOUTH; + break; } BusRenderHelper.INSTANCE.setOrientation( ax, ay, az ); @@ -256,5 +257,4 @@ public class CableRenderHelper } } } - } diff --git a/src/main/java/appeng/client/render/ItemRenderer.java b/src/main/java/appeng/client/render/ItemRenderer.java index be73c0bf7..19f483283 100644 --- a/src/main/java/appeng/client/render/ItemRenderer.java +++ b/src/main/java/appeng/client/render/ItemRenderer.java @@ -18,30 +18,32 @@ package appeng.client.render; + import org.lwjgl.opengl.GL11; import net.minecraft.item.ItemStack; import net.minecraftforge.client.IItemRenderer; + public class ItemRenderer implements IItemRenderer { public static final ItemRenderer INSTANCE = new ItemRenderer(); @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) + public boolean handleRenderType( ItemStack item, ItemRenderType type ) { return true; } @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) + public boolean shouldUseRenderHelper( ItemRenderType type, ItemStack item, ItemRendererHelper helper ) { return true; } @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) + public void renderItem( ItemRenderType type, ItemStack item, Object... data ) { GL11.glPushMatrix(); GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); @@ -51,9 +53,9 @@ public class ItemRenderer implements IItemRenderer GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - if ( type == ItemRenderType.ENTITY ) + if( type == ItemRenderType.ENTITY ) GL11.glTranslatef( -0.5f, -0.5f, -0.5f ); - if ( type == ItemRenderType.INVENTORY ) + if( type == ItemRenderType.INVENTORY ) GL11.glTranslatef( 0.0f, -0.1f, 0.0f ); WorldRender.INSTANCE.renderItemBlock( item, type, data ); @@ -61,5 +63,4 @@ public class ItemRenderer implements IItemRenderer GL11.glPopAttrib(); GL11.glPopMatrix(); } - } diff --git a/src/main/java/appeng/client/render/RenderBlocksWorkaround.java b/src/main/java/appeng/client/render/RenderBlocksWorkaround.java index 173487c5a..96e73925c 100644 --- a/src/main/java/appeng/client/render/RenderBlocksWorkaround.java +++ b/src/main/java/appeng/client/render/RenderBlocksWorkaround.java @@ -18,6 +18,7 @@ package appeng.client.render; + import java.lang.reflect.Field; import java.util.Arrays; import java.util.EnumSet; @@ -35,50 +36,600 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.api.parts.ISimplifiedBundle; import appeng.core.AELog; -@SideOnly(Side.CLIENT) + +@SideOnly( Side.CLIENT ) public class RenderBlocksWorkaround extends RenderBlocks { + final int[] lightHashTmp = new int[27]; public boolean calculations = true; public EnumSet renderFaces = EnumSet.allOf( ForgeDirection.class ); public EnumSet faces = EnumSet.allOf( ForgeDirection.class ); + public boolean isFacade = false; + public boolean useTextures = true; + public float opacity = 1.0f; + Field fBrightness; + Field fColor; + private LightingCache lightState = new LightingCache(); + + public int getCurrentColor() + { + try + { + if( this.fColor == null ) + { + try + { + this.fColor = Tessellator.class.getDeclaredField( "color" ); + } + catch( Throwable t ) + { + this.fColor = Tessellator.class.getDeclaredField( "field_78402_m" ); + } + this.fColor.setAccessible( true ); + } + return (Integer) this.fColor.get( Tessellator.instance ); + } + catch( Throwable t ) + { + return 0; + } + } + + public int getCurrentBrightness() + { + try + { + if( this.fBrightness == null ) + { + try + { + this.fBrightness = Tessellator.class.getDeclaredField( "brightness" ); + } + catch( Throwable t ) + { + this.fBrightness = Tessellator.class.getDeclaredField( "field_78401_l" ); + } + this.fBrightness.setAccessible( true ); + } + return (Integer) this.fBrightness.get( Tessellator.instance ); + } + catch( Throwable t ) + { + return 0; + } + } + + public void setTexture( IIcon ico ) + { + this.lightState.rXPos = this.lightState.rXNeg = this.lightState.rYPos = this.lightState.rYNeg = this.lightState.rZPos = this.lightState.rZNeg = ico; + } + + public void setTexture( IIcon rYNeg, IIcon rYPos, IIcon rZNeg, IIcon rZPos, IIcon rXNeg, IIcon rXPos ) + { + this.lightState.rXPos = rXPos; + this.lightState.rXNeg = rXNeg; + this.lightState.rYPos = rYPos; + this.lightState.rYNeg = rYNeg; + this.lightState.rZPos = rZPos; + this.lightState.rZNeg = rZNeg; + } + + public boolean renderStandardBlockNoCalculations( Block b, int x, int y, int z ) + { + Tessellator.instance.setBrightness( this.lightState.bXPos ); + this.restoreAO( this.lightState.aoXPos, this.lightState.foXPos ); + this.renderFaceXPos( b, x, y, z, this.useTextures ? this.lightState.rXPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.EAST.ordinal() ) ); + + Tessellator.instance.setBrightness( this.lightState.bXNeg ); + this.restoreAO( this.lightState.aoXNeg, this.lightState.foXNeg ); + this.renderFaceXNeg( b, x, y, z, this.useTextures ? this.lightState.rXNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.WEST.ordinal() ) ); + + Tessellator.instance.setBrightness( this.lightState.bYPos ); + this.restoreAO( this.lightState.aoYPos, this.lightState.foYPos ); + this.renderFaceYPos( b, x, y, z, this.useTextures ? this.lightState.rYPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.UP.ordinal() ) ); + + Tessellator.instance.setBrightness( this.lightState.bYNeg ); + this.restoreAO( this.lightState.aoYNeg, this.lightState.foYNeg ); + this.renderFaceYNeg( b, x, y, z, this.useTextures ? this.lightState.rYNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.DOWN.ordinal() ) ); + + Tessellator.instance.setBrightness( this.lightState.bZPos ); + this.restoreAO( this.lightState.aoZPos, this.lightState.foZPos ); + this.renderFaceZPos( b, x, y, z, this.useTextures ? this.lightState.rZPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.SOUTH.ordinal() ) ); + + Tessellator.instance.setBrightness( this.lightState.bZNeg ); + this.restoreAO( this.lightState.aoZNeg, this.lightState.foZNeg ); + this.renderFaceZNeg( b, x, y, z, this.useTextures ? this.lightState.rZNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.NORTH.ordinal() ) ); + + return true; + } + + private void restoreAO( int[] z, float[] c ) + { + this.brightnessBottomLeft = z[0]; + this.brightnessBottomRight = z[1]; + this.brightnessTopLeft = z[2]; + this.brightnessTopRight = z[3]; + Tessellator.instance.setColorRGBA_I( z[4], (int) ( this.opacity * 255 ) ); + + this.colorRedTopLeft = c[0]; + this.colorGreenTopLeft = c[1]; + this.colorBlueTopLeft = c[2]; + this.colorRedBottomLeft = c[3]; + this.colorGreenBottomLeft = c[4]; + this.colorBlueBottomLeft = c[5]; + this.colorRedBottomRight = c[6]; + this.colorGreenBottomRight = c[7]; + this.colorBlueBottomRight = c[8]; + this.colorRedTopRight = c[9]; + this.colorGreenTopRight = c[10]; + this.colorBlueTopRight = c[11]; + } + + private void saveAO( int[] z, float[] c ) + { + z[0] = this.brightnessBottomLeft; + z[1] = this.brightnessBottomRight; + z[2] = this.brightnessTopLeft; + z[3] = this.brightnessTopRight; + z[4] = this.getCurrentColor(); + + c[0] = this.colorRedTopLeft; + c[1] = this.colorGreenTopLeft; + c[2] = this.colorBlueTopLeft; + c[3] = this.colorRedBottomLeft; + c[4] = this.colorGreenBottomLeft; + c[5] = this.colorBlueBottomLeft; + c[6] = this.colorRedBottomRight; + c[7] = this.colorGreenBottomRight; + c[8] = this.colorBlueBottomRight; + c[9] = this.colorRedTopRight; + c[10] = this.colorGreenTopRight; + c[11] = this.colorBlueTopRight; + } + + @Override + public boolean renderStandardBlock( Block blk, int x, int y, int z ) + { + try + { + if( this.calculations ) + { + this.lightState.lightHash = this.getLightingHash( blk, this.blockAccess, x, y, z ); + return super.renderStandardBlock( blk, x, y, z ); + } + else + { + this.enableAO = this.lightState.isAO; + boolean out = this.renderStandardBlockNoCalculations( blk, x, y, z ); + this.enableAO = false; + return out; + } + } + catch( Throwable t ) + { + AELog.error( t ); + // meh + } + return false; + } + + @Override + public void renderFaceYNeg( Block par1Block, double par2, double par4, double par6, IIcon par8Icon ) + { + if( this.faces.contains( ForgeDirection.DOWN ) ) + { + if( !this.renderFaces.contains( ForgeDirection.DOWN ) ) + return; + + if( this.isFacade ) + { + Tessellator tessellator = Tessellator.instance; + + double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); + double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); + double d5 = par8Icon.getInterpolatedV( this.renderMinZ * 16.0D ); + double d6 = par8Icon.getInterpolatedV( this.renderMaxZ * 16.0D ); + + double d11 = par2 + this.renderMinX; + double d12 = par2 + this.renderMaxX; + double d13 = par4 + this.renderMinY; + double d14 = par6 + this.renderMinZ; + double d15 = par6 + this.renderMaxZ; + + if( this.enableAO ) + { + this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMaxZ ); + tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); + this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMinZ ); + tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); + this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMinZ ); + tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); + this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMaxZ ); + tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); + } + else + { + tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); + tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); + tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); + tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); + } + } + else + super.renderFaceYNeg( par1Block, par2, par4, par6, par8Icon ); + } + else + { + this.lightState.isAO = this.enableAO; + this.lightState.rYNeg = par8Icon; + this.saveAO( this.lightState.aoYNeg, this.lightState.foYNeg ); + this.lightState.bYNeg = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceYPos( Block par1Block, double par2, double par4, double par6, IIcon par8Icon ) + { + if( this.faces.contains( ForgeDirection.UP ) ) + { + if( !this.renderFaces.contains( ForgeDirection.UP ) ) + return; + + if( this.isFacade ) + { + Tessellator tessellator = Tessellator.instance; + + double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); + double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); + double d5 = par8Icon.getInterpolatedV( this.renderMinZ * 16.0D ); + double d6 = par8Icon.getInterpolatedV( this.renderMaxZ * 16.0D ); + + double d11 = par2 + this.renderMinX; + double d12 = par2 + this.renderMaxX; + double d13 = par4 + this.renderMaxY; + double d14 = par6 + this.renderMinZ; + double d15 = par6 + this.renderMaxZ; + + if( this.enableAO ) + { + this.partialLightingColoring( this.renderMaxX, this.renderMaxZ ); + tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); + this.partialLightingColoring( this.renderMaxX, this.renderMinZ ); + tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); + this.partialLightingColoring( this.renderMinX, this.renderMinZ ); + tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); + this.partialLightingColoring( this.renderMinX, this.renderMaxZ ); + tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); + } + else + { + tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); + tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); + tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); + tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); + } + } + else + super.renderFaceYPos( par1Block, par2, par4, par6, par8Icon ); + } + else + { + this.lightState.isAO = this.enableAO; + this.lightState.rYPos = par8Icon; + this.saveAO( this.lightState.aoYPos, this.lightState.foYPos ); + this.lightState.bYPos = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceZNeg( Block par1Block, double par2, double par4, double par6, IIcon par8Icon ) + { + if( this.faces.contains( ForgeDirection.NORTH ) ) + { + if( !this.renderFaces.contains( ForgeDirection.NORTH ) ) + return; + + if( this.isFacade ) + { + Tessellator tessellator = Tessellator.instance; + + double d3 = par8Icon.getInterpolatedU( 16.0D - this.renderMinX * 16.0D ); + double d4 = par8Icon.getInterpolatedU( 16.0D - this.renderMaxX * 16.0D ); + double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); + double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); + + double d11 = par2 + this.renderMinX; + double d12 = par2 + this.renderMaxX; + double d13 = par4 + this.renderMinY; + double d14 = par4 + this.renderMaxY; + double d15 = par6 + this.renderMinZ; + + if( this.enableAO ) + { + this.partialLightingColoring( this.renderMaxY, 1.0 - this.renderMinX ); + tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); + this.partialLightingColoring( this.renderMaxY, 1.0 - this.renderMaxX ); + tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); + this.partialLightingColoring( this.renderMinY, 1.0 - this.renderMaxX ); + tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); + this.partialLightingColoring( this.renderMinY, 1.0 - this.renderMinX ); + tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); + } + else + { + tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); + tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); + tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); + tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); + } + } + else + super.renderFaceZNeg( par1Block, par2, par4, par6, par8Icon ); + } + else + { + this.lightState.isAO = this.enableAO; + this.lightState.rZNeg = par8Icon; + this.saveAO( this.lightState.aoZNeg, this.lightState.foZNeg ); + this.lightState.bZNeg = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceZPos( Block par1Block, double par2, double par4, double par6, IIcon par8Icon ) + { + if( this.faces.contains( ForgeDirection.SOUTH ) ) + { + if( !this.renderFaces.contains( ForgeDirection.SOUTH ) ) + return; + + if( this.isFacade ) + { + Tessellator tessellator = Tessellator.instance; + + double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); + double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); + double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); + double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); + + double d11 = par2 + this.renderMinX; + double d12 = par2 + this.renderMaxX; + double d13 = par4 + this.renderMinY; + double d14 = par4 + this.renderMaxY; + double d15 = par6 + this.renderMaxZ; + + if( this.enableAO ) + { + this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMaxY ); + tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); + this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMinY ); + tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); + this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMinY ); + tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); + this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMaxY ); + tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); + } + else + { + tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); + tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); + tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); + tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); + } + } + else + super.renderFaceZPos( par1Block, par2, par4, par6, par8Icon ); + } + else + { + this.lightState.isAO = this.enableAO; + this.lightState.rZPos = par8Icon; + this.saveAO( this.lightState.aoZPos, this.lightState.foZPos ); + this.lightState.bZPos = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceXNeg( Block par1Block, double par2, double par4, double par6, IIcon par8Icon ) + { + if( this.faces.contains( ForgeDirection.WEST ) ) + { + if( !this.renderFaces.contains( ForgeDirection.WEST ) ) + return; + + if( this.isFacade ) + { + Tessellator tessellator = Tessellator.instance; + + double d3 = par8Icon.getInterpolatedU( this.renderMinZ * 16.0D ); + double d4 = par8Icon.getInterpolatedU( this.renderMaxZ * 16.0D ); + double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); + double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); + + double d11 = par2 + this.renderMinX; + double d12 = par4 + this.renderMinY; + double d13 = par4 + this.renderMaxY; + double d14 = par6 + this.renderMinZ; + double d15 = par6 + this.renderMaxZ; + + if( this.enableAO ) + { + this.partialLightingColoring( this.renderMaxY, this.renderMaxZ ); + tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); + this.partialLightingColoring( this.renderMaxY, this.renderMinZ ); + tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); + this.partialLightingColoring( this.renderMinY, this.renderMinZ ); + tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); + this.partialLightingColoring( this.renderMinY, this.renderMaxZ ); + tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); + } + else + { + tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); + tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); + tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); + tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); + } + } + else + super.renderFaceXNeg( par1Block, par2, par4, par6, par8Icon ); + } + else + { + this.lightState.isAO = this.enableAO; + this.lightState.rXNeg = par8Icon; + this.saveAO( this.lightState.aoXNeg, this.lightState.foXNeg ); + this.lightState.bXNeg = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceXPos( Block par1Block, double par2, double par4, double par6, IIcon par8Icon ) + { + if( this.faces.contains( ForgeDirection.EAST ) ) + { + if( !this.renderFaces.contains( ForgeDirection.EAST ) ) + return; + + if( this.isFacade ) + { + Tessellator tessellator = Tessellator.instance; + + double d3 = par8Icon.getInterpolatedU( 16.0D - this.renderMinZ * 16.0D ); + double d4 = par8Icon.getInterpolatedU( 16.0D - this.renderMaxZ * 16.0D ); + double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); + double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); + + double d11 = par2 + this.renderMaxX; + double d12 = par4 + this.renderMinY; + double d13 = par4 + this.renderMaxY; + double d14 = par6 + this.renderMinZ; + double d15 = par6 + this.renderMaxZ; + + if( this.enableAO ) + { + this.partialLightingColoring( 1.0 - this.renderMinY, this.renderMaxZ ); + tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); + this.partialLightingColoring( 1.0 - this.renderMinY, this.renderMinZ ); + tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); + this.partialLightingColoring( 1.0 - this.renderMaxY, this.renderMinZ ); + tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); + this.partialLightingColoring( 1.0 - this.renderMaxY, this.renderMaxZ ); + tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); + } + else + { + tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); + tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); + tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); + tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); + } + } + else + super.renderFaceXPos( par1Block, par2, par4, par6, par8Icon ); + } + else + { + this.lightState.isAO = this.enableAO; + this.lightState.rXPos = par8Icon; + this.saveAO( this.lightState.aoXPos, this.lightState.foXPos ); + this.lightState.bXPos = this.getCurrentBrightness(); + } + } + + private void partialLightingColoring( double u, double v ) + { + double rA = this.colorRedTopLeft * u + ( 1.0 - u ) * this.colorRedTopRight; + double rB = this.colorRedBottomLeft * u + ( 1.0 - u ) * this.colorRedBottomRight; + float r = (float) ( rA * v + rB * ( 1.0 - v ) ); + + double gA = this.colorGreenTopLeft * u + ( 1.0 - u ) * this.colorGreenTopRight; + double gB = this.colorGreenBottomLeft * u + ( 1.0 - u ) * this.colorGreenBottomRight; + float g = (float) ( gA * v + gB * ( 1.0 - v ) ); + + double bA = this.colorBlueTopLeft * u + ( 1.0 - u ) * this.colorBlueTopRight; + double bB = this.colorBlueBottomLeft * u + ( 1.0 - u ) * this.colorBlueBottomRight; + float b = (float) ( bA * v + bB * ( 1.0 - v ) ); + + double highA = ( this.brightnessTopLeft >> 16 & 255 ) * u + ( 1.0 - u ) * ( this.brightnessTopRight >> 16 & 255 ); + double highB = ( this.brightnessBottomLeft >> 16 & 255 ) * u + ( 1.0 - u ) * ( this.brightnessBottomRight >> 16 & 255 ); + int high = ( (int) ( highA * v + highB * ( 1.0 - v ) ) ) & 255; + + double lowA = ( ( this.brightnessTopLeft & 255 ) ) * u + ( 1.0 - u ) * ( ( this.brightnessTopRight & 255 ) ); + double lowB = ( ( this.brightnessBottomLeft & 255 ) ) * u + ( 1.0 - u ) * ( ( this.brightnessBottomRight & 255 ) ); + int low = ( (int) ( lowA * v + lowB * ( 1.0 - v ) ) ) & 255; + + int out = ( high << 16 ) | low; + + Tessellator.instance.setColorRGBA_F( r, g, b, this.opacity ); + Tessellator.instance.setBrightness( out ); + } + + public boolean similarLighting( Block blk, IBlockAccess w, int x, int y, int z, ISimplifiedBundle sim ) + { + int lh = this.getLightingHash( blk, w, x, y, z ); + return ( (LightingCache) sim ).lightHash == lh; + } + + private int getLightingHash( Block blk, IBlockAccess w, int x, int y, int z ) + { + int o = 0; + + for( int i = -1; i <= 1; i++ ) + for( int j = -1; j <= 1; j++ ) + for( int k = -1; k <= 1; k++ ) + { + + this.lightHashTmp[o] = blk.getMixedBrightnessForBlock( this.blockAccess, x + i, y + j, z + k ); + o++; + } + + return Arrays.hashCode( this.lightHashTmp ); + } + + public void populate( ISimplifiedBundle sim ) + { + this.lightState = new LightingCache( (LightingCache) sim ); + } + + public ISimplifiedBundle getLightingCache() + { + return new LightingCache( this.lightState ); + } private static class LightingCache implements ISimplifiedBundle { - public IIcon rXPos; - public IIcon rXNeg; - public IIcon rYPos; - public IIcon rYNeg; - public IIcon rZPos; - public IIcon rZNeg; - - public boolean isAO; - - public int bXPos; - public int bXNeg; - public int bYPos; - public int bYNeg; - public int bZPos; - public int bZNeg; - public final int[] aoXPos; public final int[] aoXNeg; public final int[] aoYPos; public final int[] aoYNeg; public final int[] aoZPos; public final int[] aoZNeg; - public final float[] foXPos; public final float[] foXNeg; public final float[] foYPos; public final float[] foYNeg; public final float[] foZPos; public final float[] foZNeg; - + public IIcon rXPos; + public IIcon rXNeg; + public IIcon rYPos; + public IIcon rYNeg; + public IIcon rZPos; + public IIcon rZNeg; + public boolean isAO; + public int bXPos; + public int bXNeg; + public int bYPos; + public int bYNeg; + public int bZPos; + public int bZNeg; public int lightHash; - public LightingCache(LightingCache secondCSrc) { + public LightingCache( LightingCache secondCSrc ) + { this.rXPos = secondCSrc.rXPos; this.rXNeg = secondCSrc.rXNeg; this.rYPos = secondCSrc.rYPos; @@ -112,7 +663,8 @@ public class RenderBlocksWorkaround extends RenderBlocks this.lightHash = secondCSrc.lightHash; } - public LightingCache() { + public LightingCache() + { this.rXPos = null; this.rXNeg = null; this.rYPos = null; @@ -145,563 +697,5 @@ public class RenderBlocksWorkaround extends RenderBlocks this.lightHash = 0; } - - } - - private LightingCache lightState = new LightingCache(); - - public boolean isFacade = false; - public boolean useTextures = true; - - Field fBrightness; - Field fColor; - - public int getCurrentColor() - { - try - { - if ( this.fColor == null ) - { - try - { - this.fColor = Tessellator.class.getDeclaredField( "color" ); - } - catch (Throwable t) - { - this.fColor = Tessellator.class.getDeclaredField( "field_78402_m" ); - } - this.fColor.setAccessible( true ); - } - return (Integer) this.fColor.get( Tessellator.instance ); - } - catch (Throwable t) - { - return 0; - } - } - - public int getCurrentBrightness() - { - try - { - if ( this.fBrightness == null ) - { - try - { - this.fBrightness = Tessellator.class.getDeclaredField( "brightness" ); - } - catch (Throwable t) - { - this.fBrightness = Tessellator.class.getDeclaredField( "field_78401_l" ); - } - this.fBrightness.setAccessible( true ); - } - return (Integer) this.fBrightness.get( Tessellator.instance ); - } - catch (Throwable t) - { - return 0; - } - } - - public void setTexture(IIcon ico) - { - this.lightState.rXPos = this.lightState.rXNeg = this.lightState.rYPos = this.lightState.rYNeg = this.lightState.rZPos = this.lightState.rZNeg = ico; - } - - public void setTexture(IIcon rYNeg, IIcon rYPos, IIcon rZNeg, IIcon rZPos, IIcon rXNeg, IIcon rXPos) - { - this.lightState.rXPos = rXPos; - this.lightState.rXNeg = rXNeg; - this.lightState.rYPos = rYPos; - this.lightState.rYNeg = rYNeg; - this.lightState.rZPos = rZPos; - this.lightState.rZNeg = rZNeg; - } - - public boolean renderStandardBlockNoCalculations(Block b, int x, int y, int z) - { - Tessellator.instance.setBrightness( this.lightState.bXPos ); - this.restoreAO( this.lightState.aoXPos, this.lightState.foXPos ); - this.renderFaceXPos( b, x, y, z, this.useTextures ? this.lightState.rXPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.EAST.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bXNeg ); - this.restoreAO( this.lightState.aoXNeg, this.lightState.foXNeg ); - this.renderFaceXNeg( b, x, y, z, this.useTextures ? this.lightState.rXNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.WEST.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bYPos ); - this.restoreAO( this.lightState.aoYPos, this.lightState.foYPos ); - this.renderFaceYPos( b, x, y, z, this.useTextures ? this.lightState.rYPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.UP.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bYNeg ); - this.restoreAO( this.lightState.aoYNeg, this.lightState.foYNeg ); - this.renderFaceYNeg( b, x, y, z, this.useTextures ? this.lightState.rYNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.DOWN.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bZPos ); - this.restoreAO( this.lightState.aoZPos, this.lightState.foZPos ); - this.renderFaceZPos( b, x, y, z, this.useTextures ? this.lightState.rZPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.SOUTH.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bZNeg ); - this.restoreAO( this.lightState.aoZNeg, this.lightState.foZNeg ); - this.renderFaceZNeg( b, x, y, z, this.useTextures ? this.lightState.rZNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.NORTH.ordinal() ) ); - - return true; - } - - private void restoreAO(int[] z, float[] c) - { - this.brightnessBottomLeft = z[0]; - this.brightnessBottomRight = z[1]; - this.brightnessTopLeft = z[2]; - this.brightnessTopRight = z[3]; - Tessellator.instance.setColorRGBA_I( z[4], (int) (this.opacity * 255) ); - - this.colorRedTopLeft = c[0]; - this.colorGreenTopLeft = c[1]; - this.colorBlueTopLeft = c[2]; - this.colorRedBottomLeft = c[3]; - this.colorGreenBottomLeft = c[4]; - this.colorBlueBottomLeft = c[5]; - this.colorRedBottomRight = c[6]; - this.colorGreenBottomRight = c[7]; - this.colorBlueBottomRight = c[8]; - this.colorRedTopRight = c[9]; - this.colorGreenTopRight = c[10]; - this.colorBlueTopRight = c[11]; - } - - private void saveAO(int[] z, float[] c) - { - z[0] = this.brightnessBottomLeft; - z[1] = this.brightnessBottomRight; - z[2] = this.brightnessTopLeft; - z[3] = this.brightnessTopRight; - z[4] = this.getCurrentColor(); - - c[0] = this.colorRedTopLeft; - c[1] = this.colorGreenTopLeft; - c[2] = this.colorBlueTopLeft; - c[3] = this.colorRedBottomLeft; - c[4] = this.colorGreenBottomLeft; - c[5] = this.colorBlueBottomLeft; - c[6] = this.colorRedBottomRight; - c[7] = this.colorGreenBottomRight; - c[8] = this.colorBlueBottomRight; - c[9] = this.colorRedTopRight; - c[10] = this.colorGreenTopRight; - c[11] = this.colorBlueTopRight; - } - - @Override - public boolean renderStandardBlock(Block blk, int x, int y, int z) - { - try - { - if ( this.calculations ) - { - this.lightState.lightHash = this.getLightingHash( blk, this.blockAccess, x, y, z ); - return super.renderStandardBlock( blk, x, y, z ); - } - else - { - this.enableAO = this.lightState.isAO; - boolean out = this.renderStandardBlockNoCalculations( blk, x, y, z ); - this.enableAO = false; - return out; - } - } - catch (Throwable t) - { - AELog.error( t ); - // meh - } - return false; - } - - @Override - public void renderFaceXNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) - { - if ( this.faces.contains( ForgeDirection.WEST ) ) - { - if ( !this.renderFaces.contains( ForgeDirection.WEST ) ) - return; - - if ( this.isFacade ) - { - Tessellator tessellator = Tessellator.instance; - - double d3 = par8Icon.getInterpolatedU( this.renderMinZ * 16.0D ); - double d4 = par8Icon.getInterpolatedU( this.renderMaxZ * 16.0D ); - double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - double d11 = par2 + this.renderMinX; - double d12 = par4 + this.renderMinY; - double d13 = par4 + this.renderMaxY; - double d14 = par6 + this.renderMinZ; - double d15 = par6 + this.renderMaxZ; - - if ( this.enableAO ) - { - this.partialLightingColoring( this.renderMaxY, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); - this.partialLightingColoring( this.renderMaxY, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - this.partialLightingColoring( this.renderMinY, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); - this.partialLightingColoring( this.renderMinY, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); - } - else - { - tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); - tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); - } - } - else - super.renderFaceXNeg( par1Block, par2, par4, par6, par8Icon ); - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rXNeg = par8Icon; - this.saveAO( this.lightState.aoXNeg, this.lightState.foXNeg ); - this.lightState.bXNeg = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceXPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) - { - if ( this.faces.contains( ForgeDirection.EAST ) ) - { - if ( !this.renderFaces.contains( ForgeDirection.EAST ) ) - return; - - if ( this.isFacade ) - { - Tessellator tessellator = Tessellator.instance; - - double d3 = par8Icon.getInterpolatedU( 16.0D - this.renderMinZ * 16.0D ); - double d4 = par8Icon.getInterpolatedU( 16.0D - this.renderMaxZ * 16.0D ); - double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - double d11 = par2 + this.renderMaxX; - double d12 = par4 + this.renderMinY; - double d13 = par4 + this.renderMaxY; - double d14 = par6 + this.renderMinZ; - double d15 = par6 + this.renderMaxZ; - - if ( this.enableAO ) - { - this.partialLightingColoring( 1.0 - this.renderMinY, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); - this.partialLightingColoring( 1.0 - this.renderMinY, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); - this.partialLightingColoring( 1.0 - this.renderMaxY, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - this.partialLightingColoring( 1.0 - this.renderMaxY, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); - } - else - { - tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); - tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); - } - } - else - super.renderFaceXPos( par1Block, par2, par4, par6, par8Icon ); - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rXPos = par8Icon; - this.saveAO( this.lightState.aoXPos, this.lightState.foXPos ); - this.lightState.bXPos = this.getCurrentBrightness(); - } - } - - private void partialLightingColoring(double u, double v) - { - double rA = this.colorRedTopLeft * u + (1.0 - u) * this.colorRedTopRight; - double rB = this.colorRedBottomLeft * u + (1.0 - u) * this.colorRedBottomRight; - float r = (float) (rA * v + rB * (1.0 - v)); - - double gA = this.colorGreenTopLeft * u + (1.0 - u) * this.colorGreenTopRight; - double gB = this.colorGreenBottomLeft * u + (1.0 - u) * this.colorGreenBottomRight; - float g = (float) (gA * v + gB * (1.0 - v)); - - double bA = this.colorBlueTopLeft * u + (1.0 - u) * this.colorBlueTopRight; - double bB = this.colorBlueBottomLeft * u + (1.0 - u) * this.colorBlueBottomRight; - float b = (float) (bA * v + bB * (1.0 - v)); - - double highA = (this.brightnessTopLeft >> 16 & 255) * u + (1.0 - u) * (this.brightnessTopRight >> 16 & 255); - double highB = (this.brightnessBottomLeft >> 16 & 255) * u + (1.0 - u) * (this.brightnessBottomRight >> 16 & 255); - int high = ((int) (highA * v + highB * (1.0 - v))) & 255; - - double lowA = ((this.brightnessTopLeft & 255)) * u + (1.0 - u) * ((this.brightnessTopRight & 255)); - double lowB = ((this.brightnessBottomLeft & 255)) * u + (1.0 - u) * ((this.brightnessBottomRight & 255)); - int low = ((int) (lowA * v + lowB * (1.0 - v))) & 255; - - int out = (high << 16) | low; - - Tessellator.instance.setColorRGBA_F( r, g, b, this.opacity ); - Tessellator.instance.setBrightness( out ); - } - - @Override - public void renderFaceYNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) - { - if ( this.faces.contains( ForgeDirection.DOWN ) ) - { - if ( !this.renderFaces.contains( ForgeDirection.DOWN ) ) - return; - - if ( this.isFacade ) - { - Tessellator tessellator = Tessellator.instance; - - double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - double d5 = par8Icon.getInterpolatedV( this.renderMinZ * 16.0D ); - double d6 = par8Icon.getInterpolatedV( this.renderMaxZ * 16.0D ); - - double d11 = par2 + this.renderMinX; - double d12 = par2 + this.renderMaxX; - double d13 = par4 + this.renderMinY; - double d14 = par6 + this.renderMinZ; - double d15 = par6 + this.renderMaxZ; - - if ( this.enableAO ) - { - this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMinZ ); - tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); - this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMaxZ ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - } - else - { - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - } - } - else - super.renderFaceYNeg( par1Block, par2, par4, par6, par8Icon ); - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rYNeg = par8Icon; - this.saveAO( this.lightState.aoYNeg, this.lightState.foYNeg ); - this.lightState.bYNeg = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceYPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) - { - if ( this.faces.contains( ForgeDirection.UP ) ) - { - if ( !this.renderFaces.contains( ForgeDirection.UP ) ) - return; - - if ( this.isFacade ) - { - Tessellator tessellator = Tessellator.instance; - - double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - double d5 = par8Icon.getInterpolatedV( this.renderMinZ * 16.0D ); - double d6 = par8Icon.getInterpolatedV( this.renderMaxZ * 16.0D ); - - double d11 = par2 + this.renderMinX; - double d12 = par2 + this.renderMaxX; - double d13 = par4 + this.renderMaxY; - double d14 = par6 + this.renderMinZ; - double d15 = par6 + this.renderMaxZ; - - if ( this.enableAO ) - { - this.partialLightingColoring( this.renderMaxX, this.renderMaxZ ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - this.partialLightingColoring( this.renderMaxX, this.renderMinZ ); - tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); - this.partialLightingColoring( this.renderMinX, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - this.partialLightingColoring( this.renderMinX, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - } - else - { - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - } - } - else - super.renderFaceYPos( par1Block, par2, par4, par6, par8Icon ); - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rYPos = par8Icon; - this.saveAO( this.lightState.aoYPos, this.lightState.foYPos ); - this.lightState.bYPos = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceZNeg(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) - { - if ( this.faces.contains( ForgeDirection.NORTH ) ) - { - if ( !this.renderFaces.contains( ForgeDirection.NORTH ) ) - return; - - if ( this.isFacade ) - { - Tessellator tessellator = Tessellator.instance; - - double d3 = par8Icon.getInterpolatedU( 16.0D - this.renderMinX * 16.0D ); - double d4 = par8Icon.getInterpolatedU( 16.0D - this.renderMaxX * 16.0D ); - double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - double d11 = par2 + this.renderMinX; - double d12 = par2 + this.renderMaxX; - double d13 = par4 + this.renderMinY; - double d14 = par4 + this.renderMaxY; - double d15 = par6 + this.renderMinZ; - - if ( this.enableAO ) - { - this.partialLightingColoring( this.renderMaxY, 1.0 - this.renderMinX ); - tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); - this.partialLightingColoring( this.renderMaxY, 1.0 - this.renderMaxX ); - tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); - this.partialLightingColoring( this.renderMinY, 1.0 - this.renderMaxX ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - this.partialLightingColoring( this.renderMinY, 1.0 - this.renderMinX ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - } - else - { - tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); - tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - } - } - else - super.renderFaceZNeg( par1Block, par2, par4, par6, par8Icon ); - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rZNeg = par8Icon; - this.saveAO( this.lightState.aoZNeg, this.lightState.foZNeg ); - this.lightState.bZNeg = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceZPos(Block par1Block, double par2, double par4, double par6, IIcon par8Icon) - { - if ( this.faces.contains( ForgeDirection.SOUTH ) ) - { - if ( !this.renderFaces.contains( ForgeDirection.SOUTH ) ) - return; - - if ( this.isFacade ) - { - Tessellator tessellator = Tessellator.instance; - - double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - double d11 = par2 + this.renderMinX; - double d12 = par2 + this.renderMaxX; - double d13 = par4 + this.renderMinY; - double d14 = par4 + this.renderMaxY; - double d15 = par6 + this.renderMaxZ; - - if ( this.enableAO ) - { - this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMaxY ); - tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); - this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMinY ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMinY ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMaxY ); - tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); - } - else - { - tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); - } - } - else - super.renderFaceZPos( par1Block, par2, par4, par6, par8Icon ); - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rZPos = par8Icon; - this.saveAO( this.lightState.aoZPos, this.lightState.foZPos ); - this.lightState.bZPos = this.getCurrentBrightness(); - } - } - - public boolean similarLighting(Block blk, IBlockAccess w, int x, int y, int z, ISimplifiedBundle sim) - { - int lh = this.getLightingHash( blk, w, x, y, z ); - return ((LightingCache) sim).lightHash == lh; - } - - final int[] lightHashTmp = new int[27]; - public float opacity = 1.0f; - - private int getLightingHash(Block blk, IBlockAccess w, int x, int y, int z) - { - int o = 0; - - for (int i = -1; i <= 1; i++) - for (int j = -1; j <= 1; j++) - for (int k = -1; k <= 1; k++) - { - - this.lightHashTmp[o] = blk.getMixedBrightnessForBlock( this.blockAccess, x + i, y + j, z + k ); - o++; - } - - return Arrays.hashCode( this.lightHashTmp ); - } - - public void populate(ISimplifiedBundle sim) - { - this.lightState = new LightingCache( (LightingCache) sim ); - } - - public ISimplifiedBundle getLightingCache() - { - return new LightingCache( this.lightState ); } } diff --git a/src/main/java/appeng/client/render/SpatialSkyRender.java b/src/main/java/appeng/client/render/SpatialSkyRender.java index 793710bc8..4550b8acb 100644 --- a/src/main/java/appeng/client/render/SpatialSkyRender.java +++ b/src/main/java/appeng/client/render/SpatialSkyRender.java @@ -18,6 +18,7 @@ package appeng.client.render; + import java.util.Random; import org.lwjgl.opengl.GL11; @@ -30,24 +31,31 @@ import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraftforge.client.IRenderHandler; + public class SpatialSkyRender extends IRenderHandler { private static final SpatialSkyRender INSTANCE = new SpatialSkyRender(); private final Random random = new Random(); - private long cycle = 0; private final int dspList; + private long cycle = 0; - public SpatialSkyRender() { + public SpatialSkyRender() + { this.dspList = GLAllocation.generateDisplayLists( 1 ); } + public static IRenderHandler getInstance() + { + return INSTANCE; + } + @Override - public void render(float partialTicks, WorldClient world, Minecraft mc) + public void render( float partialTicks, WorldClient world, Minecraft mc ) { long now = System.currentTimeMillis(); - if ( now - this.cycle > 2000 ) + if( now - this.cycle > 2000 ) { this.cycle = now; GL11.glNewList( this.dspList, GL11.GL_COMPILE ); @@ -57,59 +65,59 @@ public class SpatialSkyRender extends IRenderHandler float fade = now - this.cycle; fade /= 1000; - fade = 0.15f * (1.0f - Math.abs( (fade - 1.0f) * (fade - 1.0f) )); + fade = 0.15f * ( 1.0f - Math.abs( ( fade - 1.0f ) * ( fade - 1.0f ) ) ); GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - GL11.glDisable(GL11.GL_FOG); - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glDisable(GL11.GL_BLEND); - GL11.glDepthMask(false); - GL11.glColor4f( 0.0f, 0.0f, 0.0f, 1.0f ); - Tessellator tessellator = Tessellator.instance; + GL11.glDisable( GL11.GL_FOG ); + GL11.glDisable( GL11.GL_ALPHA_TEST ); + GL11.glDisable( GL11.GL_BLEND ); + GL11.glDepthMask( false ); + GL11.glColor4f( 0.0f, 0.0f, 0.0f, 1.0f ); + Tessellator tessellator = Tessellator.instance; - for (int i = 0; i < 6; ++i) - { - GL11.glPushMatrix(); + for( int i = 0; i < 6; ++i ) + { + GL11.glPushMatrix(); - if (i == 1) - { - GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F); - } + if( i == 1 ) + { + GL11.glRotatef( 90.0F, 1.0F, 0.0F, 0.0F ); + } - if (i == 2) - { - GL11.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F); - } + if( i == 2 ) + { + GL11.glRotatef( -90.0F, 1.0F, 0.0F, 0.0F ); + } - if (i == 3) - { - GL11.glRotatef(180.0F, 1.0F, 0.0F, 0.0F); - } + if( i == 3 ) + { + GL11.glRotatef( 180.0F, 1.0F, 0.0F, 0.0F ); + } - if (i == 4) - { - GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F); - } + if( i == 4 ) + { + GL11.glRotatef( 90.0F, 0.0F, 0.0F, 1.0F ); + } - if (i == 5) - { - GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F); - } + if( i == 5 ) + { + GL11.glRotatef( -90.0F, 0.0F, 0.0F, 1.0F ); + } - tessellator.startDrawingQuads(); - tessellator.setColorOpaque_I(0); - tessellator.addVertexWithUV(-100.0D, -100.0D, -100.0D, 0.0D, 0.0D); - tessellator.addVertexWithUV(-100.0D, -100.0D, 100.0D, 0.0D, 16.0D); - tessellator.addVertexWithUV(100.0D, -100.0D, 100.0D, 16.0D, 16.0D); - tessellator.addVertexWithUV(100.0D, -100.0D, -100.0D, 16.0D, 0.0D); - tessellator.draw(); - GL11.glPopMatrix(); - } + tessellator.startDrawingQuads(); + tessellator.setColorOpaque_I( 0 ); + tessellator.addVertexWithUV( -100.0D, -100.0D, -100.0D, 0.0D, 0.0D ); + tessellator.addVertexWithUV( -100.0D, -100.0D, 100.0D, 0.0D, 16.0D ); + tessellator.addVertexWithUV( 100.0D, -100.0D, 100.0D, 16.0D, 16.0D ); + tessellator.addVertexWithUV( 100.0D, -100.0D, -100.0D, 16.0D, 0.0D ); + tessellator.draw(); + GL11.glPopMatrix(); + } - GL11.glDepthMask(true); + GL11.glDepthMask( true ); - if ( fade > 0.0f ) + if( fade > 0.0f ) { GL11.glDisable( GL11.GL_FOG ); GL11.glDisable( GL11.GL_ALPHA_TEST ); @@ -129,7 +137,7 @@ public class SpatialSkyRender extends IRenderHandler GL11.glPopAttrib(); - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); } private void renderTwinkles() @@ -137,7 +145,7 @@ public class SpatialSkyRender extends IRenderHandler Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - for (int i = 0; i < 50; ++i) + for( int i = 0; i < 50; ++i ) { double iX = this.random.nextFloat() * 2.0F - 1.0F; double iY = this.random.nextFloat() * 2.0F - 1.0F; @@ -145,7 +153,7 @@ public class SpatialSkyRender extends IRenderHandler double d3 = 0.05F + this.random.nextFloat() * 0.1F; double dist = iX * iX + iY * iY + iZ * iZ; - if ( dist < 1.0D && dist > 0.01D ) + if( dist < 1.0D && dist > 0.01D ) { dist = 1.0D / Math.sqrt( dist ); iX *= dist; @@ -164,11 +172,11 @@ public class SpatialSkyRender extends IRenderHandler double d15 = Math.sin( d14 ); double d16 = Math.cos( d14 ); - for (int j = 0; j < 4; ++j) + for( int j = 0; j < 4; ++j ) { double d17 = 0.0D; - double d18 = ((j & 2) - 1) * d3; - double d19 = ((j + 1 & 2) - 1) * d3; + double d18 = ( ( j & 2 ) - 1 ) * d3; + double d19 = ( ( j + 1 & 2 ) - 1 ) * d3; double d20 = d18 * d16 - d19 * d15; double d21 = d19 * d16 + d18 * d15; double d22 = d20 * d12 + d17 * d13; @@ -182,10 +190,4 @@ public class SpatialSkyRender extends IRenderHandler tessellator.draw(); } - - public static IRenderHandler getInstance() - { - return INSTANCE; - } - } diff --git a/src/main/java/appeng/client/render/TESRWrapper.java b/src/main/java/appeng/client/render/TESRWrapper.java index f6911cf0c..beff5d29b 100644 --- a/src/main/java/appeng/client/render/TESRWrapper.java +++ b/src/main/java/appeng/client/render/TESRWrapper.java @@ -18,6 +18,7 @@ package appeng.client.render; + import org.lwjgl.opengl.GL11; import net.minecraft.block.Block; @@ -34,7 +35,8 @@ import appeng.core.AELog; import appeng.tile.AEBaseTile; import appeng.util.Platform; -@SideOnly(Side.CLIENT) + +@SideOnly( Side.CLIENT ) public class TESRWrapper extends TileEntitySpecialRenderer { @@ -43,26 +45,27 @@ public class TESRWrapper extends TileEntitySpecialRenderer final BaseBlockRender blkRender; final double MAX_DISTANCE; - public TESRWrapper(BaseBlockRender render) { + public TESRWrapper( BaseBlockRender render ) + { this.blkRender = render; this.MAX_DISTANCE = this.blkRender.getTesrRenderDistance(); } @Override - final public void renderTileEntityAt(TileEntity te, double x, double y, double z, float f) + final public void renderTileEntityAt( TileEntity te, double x, double y, double z, float f ) { - if ( te instanceof AEBaseTile ) + if( te instanceof AEBaseTile ) { Block b = te.getBlockType(); - if ( b instanceof AEBaseBlock && ((AEBaseTile) te).requiresTESR() ) + if( b instanceof AEBaseBlock && ( (AEBaseTile) te ).requiresTESR() ) { - if ( Math.abs( x ) > this.MAX_DISTANCE || Math.abs( y ) > this.MAX_DISTANCE || Math.abs( z ) > this.MAX_DISTANCE ) + if( Math.abs( x ) > this.MAX_DISTANCE || Math.abs( y ) > this.MAX_DISTANCE || Math.abs( z ) > this.MAX_DISTANCE ) return; Tessellator tess = Tessellator.instance; - if ( Platform.isDrawing( tess ) ) + if( Platform.isDrawing( tess ) ) return; try @@ -73,20 +76,19 @@ public class TESRWrapper extends TileEntitySpecialRenderer this.renderBlocksInstance.blockAccess = te.getWorldObj(); this.blkRender.renderTile( (AEBaseBlock) b, (AEBaseTile) te, tess, x, y, z, f, this.renderBlocksInstance ); - if ( Platform.isDrawing( tess ) ) + if( Platform.isDrawing( tess ) ) throw new RuntimeException( "Error during rendering." ); GL11.glPopAttrib(); GL11.glPopMatrix(); } - catch (Throwable t) + catch( Throwable t ) { AELog.severe( "Hi, Looks like there was a crash while rendering something..." ); t.printStackTrace(); AELog.severe( "MC will now crash ( probably )!" ); throw new RuntimeException( t ); } - } } } diff --git a/src/main/java/appeng/client/render/WorldRender.java b/src/main/java/appeng/client/render/WorldRender.java index bb9a60bcc..26236c36c 100644 --- a/src/main/java/appeng/client/render/WorldRender.java +++ b/src/main/java/appeng/client/render/WorldRender.java @@ -18,6 +18,7 @@ package appeng.client.render; + import java.util.HashMap; import net.minecraft.block.Block; @@ -34,33 +35,34 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.block.AEBaseBlock; import appeng.core.AELog; -@SideOnly(Side.CLIENT) + +@SideOnly( Side.CLIENT ) public final class WorldRender implements ISimpleBlockRenderingHandler { - private final RenderBlocks renderer = new RenderBlocks(); - final int renderID = RenderingRegistry.getNextAvailableRenderId(); public static final WorldRender INSTANCE = new WorldRender(); + public final HashMap blockRenders = new HashMap(); + final int renderID = RenderingRegistry.getNextAvailableRenderId(); + private final RenderBlocks renderer = new RenderBlocks(); boolean hasError = false; - public final HashMap blockRenders = new HashMap(); + private WorldRender() + { + } - void setRender(AEBaseBlock in, BaseBlockRender r) + void setRender( AEBaseBlock in, BaseBlockRender r ) { this.blockRenders.put( in, r ); } - private WorldRender() { - } - @Override - public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) + public void renderInventoryBlock( Block block, int metadata, int modelID, RenderBlocks renderer ) { // wtf is this for? } @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) + public boolean renderWorldBlock( IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer ) { AEBaseBlock blk = (AEBaseBlock) block; renderer.setRenderBoundsFromBlock( block ); @@ -68,7 +70,7 @@ public final class WorldRender implements ISimpleBlockRenderingHandler } @Override - public boolean shouldRender3DInInventory(int modelId) + public boolean shouldRender3DInInventory( int modelId ) { return true; } @@ -79,10 +81,15 @@ public final class WorldRender implements ISimpleBlockRenderingHandler return this.renderID; } - public void renderItemBlock(ItemStack item, ItemRenderType type, Object[] data) + private BaseBlockRender getRender( AEBaseBlock block ) + { + return block.getRendererInstance().rendererInstance; + } + + public void renderItemBlock( ItemStack item, ItemRenderType type, Object[] data ) { Block blk = Block.getBlockFromItem( item.getItem() ); - if ( blk instanceof AEBaseBlock ) + if( blk instanceof AEBaseBlock ) { AEBaseBlock block = (AEBaseBlock) blk; this.renderer.setRenderBoundsFromBlock( block ); @@ -93,7 +100,7 @@ public final class WorldRender implements ISimpleBlockRenderingHandler } else { - if ( !this.hasError ) + if( !this.hasError ) { this.hasError = true; AELog.severe( "Invalid render - item/block mismatch" ); @@ -102,9 +109,4 @@ public final class WorldRender implements ISimpleBlockRenderingHandler } } } - - private BaseBlockRender getRender(AEBaseBlock block) - { - return block.getRendererInstance().rendererInstance; - } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java b/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java index d41f32c37..896510d05 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java @@ -47,90 +47,17 @@ import appeng.parts.networking.PartCable; import appeng.tile.crafting.TileMolecularAssembler; import appeng.util.Platform; + public class RenderBlockAssembler extends BaseBlockRender implements IBoxProvider { - IIcon getConnectedCable(IBlockAccess world, int x, int y, int z, ForgeDirection side, boolean covered) + public RenderBlockAssembler() { - final int tileYPos = y + side.offsetY; - if ( -1 < tileYPos && tileYPos < 256 ) - { - TileEntity ne = world.getTileEntity( x + side.offsetX, tileYPos, z + side.offsetZ ); - if ( ne instanceof IGridHost && ne instanceof IPartHost ) - { - IPartHost ph = (IPartHost) ne; - IPart pcx = ph.getPart( ForgeDirection.UNKNOWN ); - if ( pcx instanceof PartCable ) - { - PartCable pc = (PartCable) pcx; - if ( pc.isConnected( side.getOpposite() ) ) - { - if ( covered ) - return pc.getCoveredTexture( pc.getCableColor() ); - return pc.getGlassTexture( pc.getCableColor() ); - } - } - } - } - - return null; - } - - public void renderCableAt(double Thickness, IBlockAccess world, int x, int y, int z, AEBaseBlock block, RenderBlocks renderer, double pull, boolean covered) - { - IIcon texture = null; - - block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.WEST, covered ) ); - if ( texture != null ) - { - renderer.setRenderBounds( 0.0D, 0.5D - Thickness, 0.5D - Thickness, 0.5D - Thickness - pull, 0.5D + Thickness, 0.5D + Thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.EAST, covered ) ); - if ( texture != null ) - { - renderer.setRenderBounds( 0.5D + Thickness + pull, 0.5D - Thickness, 0.5D - Thickness, 1.0D, 0.5D + Thickness, 0.5D + Thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.NORTH, covered ) ); - if ( texture != null ) - { - renderer.setRenderBounds( 0.5D - Thickness, 0.5D - Thickness, 0.0D, 0.5D + Thickness, 0.5D + Thickness, 0.5D - Thickness - pull ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.SOUTH, covered ) ); - if ( texture != null ) - { - renderer.setRenderBounds( 0.5D - Thickness, 0.5D - Thickness, 0.5D + Thickness + pull, 0.5D + Thickness, 0.5D + Thickness, 1.0D ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.DOWN, covered ) ); - if ( texture != null ) - { - renderer.setRenderBounds( 0.5D - Thickness, 0.0D, 0.5D - Thickness, 0.5D + Thickness, 0.5D - Thickness - pull, 0.5D + Thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.UP, covered ) ); - if ( texture != null ) - { - renderer.setRenderBounds( 0.5D - Thickness, 0.5D + Thickness + pull, 0.5D - Thickness, 0.5D + Thickness, 1.0D, 0.5D + Thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( null ); - } - - public RenderBlockAssembler() { super( false, 20 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { renderer.setOverrideBlockTexture( blk.getIcon( 0, 0 ) ); @@ -177,14 +104,14 @@ public class RenderBlockAssembler extends BaseBlockRender implements IBoxProvide } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { BlockMolecularAssembler blk = (BlockMolecularAssembler) block; TileMolecularAssembler tma = blk.getTileEntity( world, x, y, z ); - if ( BlockMolecularAssembler.booleanAlphaPass ) + if( BlockMolecularAssembler.booleanAlphaPass ) { - if ( tma.isPowered() ) + if( tma.isPowered() ) { this.renderBlockBounds( renderer, 1, 1, 1, 15, 15, 15, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.SOUTH ); TaughtIcon lights = new TaughtIcon( ExtraBlockTextures.BlockMolecularAssemblerLights.getIcon(), -2.0f ); @@ -274,8 +201,83 @@ public class RenderBlockAssembler extends BaseBlockRender implements IBoxProvide return true; } + public void renderCableAt( double Thickness, IBlockAccess world, int x, int y, int z, AEBaseBlock block, RenderBlocks renderer, double pull, boolean covered ) + { + IIcon texture = null; + + block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.WEST, covered ) ); + if( texture != null ) + { + renderer.setRenderBounds( 0.0D, 0.5D - Thickness, 0.5D - Thickness, 0.5D - Thickness - pull, 0.5D + Thickness, 0.5D + Thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.EAST, covered ) ); + if( texture != null ) + { + renderer.setRenderBounds( 0.5D + Thickness + pull, 0.5D - Thickness, 0.5D - Thickness, 1.0D, 0.5D + Thickness, 0.5D + Thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.NORTH, covered ) ); + if( texture != null ) + { + renderer.setRenderBounds( 0.5D - Thickness, 0.5D - Thickness, 0.0D, 0.5D + Thickness, 0.5D + Thickness, 0.5D - Thickness - pull ); + renderer.renderStandardBlock( block, x, y, z ); + } + + block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.SOUTH, covered ) ); + if( texture != null ) + { + renderer.setRenderBounds( 0.5D - Thickness, 0.5D - Thickness, 0.5D + Thickness + pull, 0.5D + Thickness, 0.5D + Thickness, 1.0D ); + renderer.renderStandardBlock( block, x, y, z ); + } + + block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.DOWN, covered ) ); + if( texture != null ) + { + renderer.setRenderBounds( 0.5D - Thickness, 0.0D, 0.5D - Thickness, 0.5D + Thickness, 0.5D - Thickness - pull, 0.5D + Thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + block.getRendererInstance().setTemporaryRenderIcon( texture = this.getConnectedCable( world, x, y, z, ForgeDirection.UP, covered ) ); + if( texture != null ) + { + renderer.setRenderBounds( 0.5D - Thickness, 0.5D + Thickness + pull, 0.5D - Thickness, 0.5D + Thickness, 1.0D, 0.5D + Thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + block.getRendererInstance().setTemporaryRenderIcon( null ); + } + + IIcon getConnectedCable( IBlockAccess world, int x, int y, int z, ForgeDirection side, boolean covered ) + { + final int tileYPos = y + side.offsetY; + if( -1 < tileYPos && tileYPos < 256 ) + { + TileEntity ne = world.getTileEntity( x + side.offsetX, tileYPos, z + side.offsetZ ); + if( ne instanceof IGridHost && ne instanceof IPartHost ) + { + IPartHost ph = (IPartHost) ne; + IPart pcx = ph.getPart( ForgeDirection.UNKNOWN ); + if( pcx instanceof PartCable ) + { + PartCable pc = (PartCable) pcx; + if( pc.isConnected( side.getOpposite() ) ) + { + if( covered ) + return pc.getCoveredTexture( pc.getCableColor() ); + return pc.getGlassTexture( pc.getCableColor() ); + } + } + } + } + + return null; + } + @Override - public void getBoxes(IPartCollisionHelper bch) + public void getBoxes( IPartCollisionHelper bch ) { bch.addBox( 0, 0, 0, 16, 16, 16 ); } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCharger.java b/src/main/java/appeng/client/render/blocks/RenderBlockCharger.java index 70e662066..5a9aadf74 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCharger.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCharger.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import org.lwjgl.opengl.GL11; @@ -42,15 +43,17 @@ import appeng.core.AELog; import appeng.tile.AEBaseTile; import appeng.util.Platform; + public class RenderBlockCharger extends BaseBlockRender { - public RenderBlockCharger() { + public RenderBlockCharger() + { super( true, 30 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { Tessellator tess = Tessellator.instance; @@ -78,11 +81,10 @@ public class RenderBlockCharger extends BaseBlockRender renderer.renderAllFaces = false; blk.getRendererInstance().setTemporaryRenderIcon( null ); - } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { this.preRenderInWorld( block, world, x, y, z, renderer ); @@ -124,13 +126,13 @@ public class RenderBlockCharger extends BaseBlockRender } @Override - public void renderTile(AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer) + public void renderTile( AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer ) { ItemStack sis = null; - if ( tile instanceof IInventory ) - sis = ((IInventory) tile).getStackInSlot( 0 ); + if( tile instanceof IInventory ) + sis = ( (IInventory) tile ).getStackInSlot( 0 ); - if ( sis != null ) + if( sis != null ) { GL11.glPushMatrix(); this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); @@ -142,7 +144,7 @@ public class RenderBlockCharger extends BaseBlockRender GL11.glScalef( 1.0f, 1.0f, 1.0f ); Block blk = Block.getBlockFromItem( sis.getItem() ); - if ( sis.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( blk.getRenderType() ) ) + if( sis.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( blk.getRenderType() ) ) { GL11.glRotatef( 25.0f, 1.0f, 0.0f, 0.0f ); GL11.glRotatef( 15.0f, 0.0f, 1.0f, 0.0f ); @@ -162,7 +164,7 @@ public class RenderBlockCharger extends BaseBlockRender this.doRenderItem( sis, tile ); } - catch (Exception err) + catch( Exception err ) { AELog.error( err ); } @@ -170,5 +172,4 @@ public class RenderBlockCharger extends BaseBlockRender GL11.glPopMatrix(); } } - } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockController.java b/src/main/java/appeng/client/render/blocks/RenderBlockController.java index 940f13121..89462434a 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockController.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockController.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; @@ -28,15 +29,17 @@ import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.networking.TileController; + public class RenderBlockController extends BaseBlockRender { - public RenderBlockController() { + public RenderBlockController() + { super( false, 20 ); } @Override - public boolean renderInWorld(AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { boolean xx = this.getTileEntity( world, x - 1, y, z ) instanceof TileController && this.getTileEntity( world, x + 1, y, z ) instanceof TileController; @@ -49,12 +52,12 @@ public class RenderBlockController extends BaseBlockRender ExtraBlockTextures lights = null; - if ( xx && !yy && !zz ) + if( xx && !yy && !zz ) { - if ( hasPower ) + if( hasPower ) { blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if ( isConflict ) + if( isConflict ) lights = ExtraBlockTextures.BlockControllerColumnConflict; else lights = ExtraBlockTextures.BlockControllerColumnLights; @@ -67,12 +70,12 @@ public class RenderBlockController extends BaseBlockRender renderer.uvRotateTop = 1; renderer.uvRotateBottom = 1; } - else if ( !xx && yy && !zz ) + else if( !xx && yy && !zz ) { - if ( hasPower ) + if( hasPower ) { blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if ( isConflict ) + if( isConflict ) lights = ExtraBlockTextures.BlockControllerColumnConflict; else lights = ExtraBlockTextures.BlockControllerColumnLights; @@ -83,12 +86,12 @@ public class RenderBlockController extends BaseBlockRender renderer.uvRotateEast = 0; renderer.uvRotateNorth = 0; } - else if ( !xx && !yy && zz ) + else if( !xx && !yy && zz ) { - if ( hasPower ) + if( hasPower ) { blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if ( isConflict ) + if( isConflict ) lights = ExtraBlockTextures.BlockControllerColumnConflict; else lights = ExtraBlockTextures.BlockControllerColumnLights; @@ -100,33 +103,32 @@ public class RenderBlockController extends BaseBlockRender renderer.uvRotateSouth = 1; renderer.uvRotateTop = 0; } - else if ( (xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) >= 2 ) + else if( ( xx ? 1 : 0 ) + ( yy ? 1 : 0 ) + ( zz ? 1 : 0 ) >= 2 ) { - int v = (Math.abs( x ) + Math.abs( y ) + Math.abs( z )) % 2; + int v = ( Math.abs( x ) + Math.abs( y ) + Math.abs( z ) ) % 2; renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - if ( v == 0 ) + if( v == 0 ) blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerInsideA.getIcon() ); else blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerInsideB.getIcon() ); } else { - if ( hasPower ) + if( hasPower ) { blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerPowered.getIcon() ); - if ( isConflict ) + if( isConflict ) lights = ExtraBlockTextures.BlockControllerConflict; else lights = ExtraBlockTextures.BlockControllerLights; } else blk.getRendererInstance().setTemporaryRenderIcon( null ); - } boolean out = renderer.renderStandardBlock( blk, x, y, z ); - if ( lights != null ) + if( lights != null ) { Tessellator.instance.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); Tessellator.instance.setBrightness( 14 << 20 | 14 << 4 ); @@ -143,9 +145,9 @@ public class RenderBlockController extends BaseBlockRender return out; } - private TileEntity getTileEntity(IBlockAccess world, int x, int y, int z) + private TileEntity getTileEntity( IBlockAccess world, int x, int y, int z ) { - if ( y >= 0 ) + if( y >= 0 ) return world.getTileEntity( x, y, z ); return null; } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPU.java b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPU.java index 4c5309415..8a384544e 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPU.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPU.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import net.minecraft.block.Block; @@ -40,26 +41,29 @@ import appeng.client.texture.ExtraBlockTextures; import appeng.tile.crafting.TileCraftingMonitorTile; import appeng.tile.crafting.TileCraftingTile; + public class RenderBlockCraftingCPU extends BaseBlockRender { - protected RenderBlockCraftingCPU(boolean useTESR, int range) { + protected RenderBlockCraftingCPU( boolean useTESR, int range ) + { super( useTESR, range ); } - public RenderBlockCraftingCPU() { + public RenderBlockCraftingCPU() + { super( false, 20 ); } @Override - public boolean renderInWorld(AEBaseBlock blk, IBlockAccess w, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock blk, IBlockAccess w, int x, int y, int z, RenderBlocks renderer ) { IIcon theIcon = null; boolean formed = false; boolean emitsLight = false; TileCraftingTile ct = blk.getTileEntity( w, x, y, z ); - if ( ct != null && ct.isFormed() ) + if( ct != null && ct.isFormed() ) { formed = true; emitsLight = ct.isPowered(); @@ -67,18 +71,18 @@ public class RenderBlockCraftingCPU extends BaseBlockRender int meta = w.getBlockMetadata( x, y, z ) & 3; boolean isMonitor = blk.getClass() == BlockCraftingMonitor.class; - theIcon = blk.getIcon( ForgeDirection.SOUTH.ordinal(), meta | (formed ? 8 : 0) ); + theIcon = blk.getIcon( ForgeDirection.SOUTH.ordinal(), meta | ( formed ? 8 : 0 ) ); IIcon nonForward = theIcon; - if ( isMonitor ) + if( isMonitor ) { - for ( Block craftingBlock : AEApi.instance().definitions().blocks().craftingUnit().maybeBlock().asSet() ) + for( Block craftingBlock : AEApi.instance().definitions().blocks().craftingUnit().maybeBlock().asSet() ) { nonForward = craftingBlock.getIcon( 0, meta | ( formed ? 8 : 0 ) ); } } - if ( formed && renderer.overrideBlockTexture == null ) + if( formed && renderer.overrideBlockTexture == null ) { renderer = BusRenderer.INSTANCE.renderer; BusRenderHelper i = BusRenderHelper.INSTANCE; @@ -92,7 +96,7 @@ public class RenderBlockCraftingCPU extends BaseBlockRender { ct.lightCache = i.useSimplifiedRendering( x, y, z, null, ct.lightCache ); } - catch (Throwable ignored) + catch( Throwable ignored ) { } @@ -115,14 +119,13 @@ public class RenderBlockCraftingCPU extends BaseBlockRender this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.NORTH ); this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.SOUTH ); - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) { - i.setBounds( this.fso( side, lowX, ForgeDirection.WEST ), this.fso( side, lowY, ForgeDirection.DOWN ), this.fso( side, lowZ, ForgeDirection.NORTH ), - this.fso( side, highX, ForgeDirection.EAST ), this.fso( side, highY, ForgeDirection.UP ), this.fso( side, highZ, ForgeDirection.SOUTH ) ); + i.setBounds( this.fso( side, lowX, ForgeDirection.WEST ), this.fso( side, lowY, ForgeDirection.DOWN ), this.fso( side, lowZ, ForgeDirection.NORTH ), this.fso( side, highX, ForgeDirection.EAST ), this.fso( side, highY, ForgeDirection.UP ), this.fso( side, highZ, ForgeDirection.SOUTH ) ); i.prepareBounds( renderer ); boolean LocalEmit = emitsLight; - if ( blk instanceof BlockCraftingMonitor && ct.getForward() != side ) + if( blk instanceof BlockCraftingMonitor && ct.getForward() != side ) LocalEmit = false; this.handleSide( blk, meta, x, y, z, i, renderer, ct.getForward() == side ? theIcon : nonForward, LocalEmit, isMonitor, side, w ); @@ -144,74 +147,75 @@ public class RenderBlockCraftingCPU extends BaseBlockRender } } - private void renderCorner(BusRenderHelper i, RenderBlocks renderer, IBlockAccess w, int x, int y, int z, ForgeDirection up, ForgeDirection east, - ForgeDirection south) + private boolean isConnected( IBlockAccess w, int x, int y, int z, ForgeDirection side ) { - if ( this.isConnected( w, x, y, z, up ) ) + final int tileYPos = y + side.offsetY; + if( 0 <= tileYPos && tileYPos <= 255 ) + { + final TileEntity tile = w.getTileEntity( x + side.offsetX, tileYPos, z + side.offsetZ ); + + return tile instanceof TileCraftingTile; + } + else + { + return false; + } + } + + private void renderCorner( BusRenderHelper i, RenderBlocks renderer, IBlockAccess w, int x, int y, int z, ForgeDirection up, ForgeDirection east, ForgeDirection south ) + { + if( this.isConnected( w, x, y, z, up ) ) return; - if ( this.isConnected( w, x, y, z, east ) ) + if( this.isConnected( w, x, y, z, east ) ) return; - if ( this.isConnected( w, x, y, z, south ) ) + if( this.isConnected( w, x, y, z, south ) ) return; - i.setBounds( this.gso( east, 3, ForgeDirection.WEST ), this.gso( up, 3, ForgeDirection.DOWN ), this.gso( south, 3, ForgeDirection.NORTH ), - this.gso( east, 13, ForgeDirection.EAST ), this.gso( up, 13, ForgeDirection.UP ), this.gso( south, 13, ForgeDirection.SOUTH ) ); + i.setBounds( this.gso( east, 3, ForgeDirection.WEST ), this.gso( up, 3, ForgeDirection.DOWN ), this.gso( south, 3, ForgeDirection.NORTH ), this.gso( east, 13, ForgeDirection.EAST ), this.gso( up, 13, ForgeDirection.UP ), this.gso( south, 13, ForgeDirection.SOUTH ) ); i.prepareBounds( renderer ); i.setTexture( ExtraBlockTextures.BlockCraftingUnitRing.getIcon() ); i.renderBlockCurrentBounds( x, y, z, renderer ); } - private float gso(ForgeDirection side, float def, ForgeDirection target) + private float fso( ForgeDirection side, float def, ForgeDirection target ) { - if ( side != target ) + if( side == target ) { - if ( side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0 ) + if( side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0 ) return 16; return 0; } return def; } - private float fso(ForgeDirection side, float def, ForgeDirection target) + private void handleSide( AEBaseBlock blk, int meta, int x, int y, int z, BusRenderHelper i, RenderBlocks renderer, IIcon color, boolean emitsLight, boolean isMonitor, ForgeDirection side, IBlockAccess w ) { - if ( side == target ) - { - if ( side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0 ) - return 16; - return 0; - } - return def; - } - - private void handleSide(AEBaseBlock blk, int meta, int x, int y, int z, BusRenderHelper i, RenderBlocks renderer, IIcon color, boolean emitsLight, - boolean isMonitor, ForgeDirection side, IBlockAccess w) - { - if ( this.isConnected( w, x, y, z, side ) ) + if( this.isConnected( w, x, y, z, side ) ) return; i.setFacesToRender( EnumSet.of( side ) ); - if ( meta == 0 && blk.getClass() == BlockCraftingUnit.class ) + if( meta == 0 && blk.getClass() == BlockCraftingUnit.class ) { i.setTexture( ExtraBlockTextures.BlockCraftingUnitFit.getIcon() ); i.renderBlockCurrentBounds( x, y, z, renderer ); } else { - if ( color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon() ) + if( color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon() ) i.setTexture( ExtraBlockTextures.BlockCraftingMonitorOuter.getIcon() ); else i.setTexture( ExtraBlockTextures.BlockCraftingFitSolid.getIcon() ); i.renderBlockCurrentBounds( x, y, z, renderer ); - if ( color != null ) + if( color != null ) { i.setTexture( color ); - if ( !emitsLight ) + if( !emitsLight ) { - if ( color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon() ) + if( color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon() ) { int b = w.getLightBrightnessForSkyBlocks( x + side.offsetX, y + side.offsetY, z + side.offsetZ, 0 ); @@ -233,7 +237,7 @@ public class RenderBlockCraftingCPU extends BaseBlockRender } else { - if ( isMonitor ) + if( isMonitor ) { TileCraftingMonitorTile sr = blk.getTileEntity( w, x, y, z ); AEColor col = sr.getColor(); @@ -257,68 +261,66 @@ public class RenderBlockCraftingCPU extends BaseBlockRender i.renderFace( x, y, z, color, side, renderer ); } } - } } - for (ForgeDirection a : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection a : ForgeDirection.VALID_DIRECTIONS ) { - if ( a == side || a == side.getOpposite() ) + if( a == side || a == side.getOpposite() ) continue; - if ( (side.offsetX != 0 || side.offsetZ != 0) - && (a == ForgeDirection.NORTH || a == ForgeDirection.EAST || a == ForgeDirection.WEST || a == ForgeDirection.SOUTH) ) + if( ( side.offsetX != 0 || side.offsetZ != 0 ) && ( a == ForgeDirection.NORTH || a == ForgeDirection.EAST || a == ForgeDirection.WEST || a == ForgeDirection.SOUTH ) ) i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon() ); - else if ( (side.offsetY != 0) && (a == ForgeDirection.EAST || a == ForgeDirection.WEST) ) + else if( ( side.offsetY != 0 ) && ( a == ForgeDirection.EAST || a == ForgeDirection.WEST ) ) i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon() ); else i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLong.getIcon() ); double width = 3.0 / 16.0; - if ( !(i.getBound( a ) < 0.001 || i.getBound( a ) > 15.999) ) + if( !( i.getBound( a ) < 0.001 || i.getBound( a ) > 15.999 ) ) { - switch (a) + switch( a ) { - case DOWN: - renderer.renderMinY = 0; - renderer.renderMaxY = width; - break; - case EAST: - renderer.renderMaxX = 1; - renderer.renderMinX = 1.0 - width; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 1; - renderer.uvRotateWest = 1; - renderer.uvRotateEast = 1; - break; - case NORTH: - renderer.renderMinZ = 0; - renderer.renderMaxZ = width; - renderer.uvRotateWest = 1; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 1; - break; - case SOUTH: - renderer.renderMaxZ = 1; - renderer.renderMinZ = 1.0 - width; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 1; - break; - case UP: - renderer.renderMaxY = 1; - renderer.renderMinY = 1.0 - width; - break; - case WEST: - renderer.renderMinX = 0; - renderer.renderMaxX = width; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 1; - renderer.uvRotateWest = 1; - renderer.uvRotateEast = 1; - break; - case UNKNOWN: - default: + case DOWN: + renderer.renderMinY = 0; + renderer.renderMaxY = width; + break; + case EAST: + renderer.renderMaxX = 1; + renderer.renderMinX = 1.0 - width; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 1; + renderer.uvRotateWest = 1; + renderer.uvRotateEast = 1; + break; + case NORTH: + renderer.renderMinZ = 0; + renderer.renderMaxZ = width; + renderer.uvRotateWest = 1; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 1; + break; + case SOUTH: + renderer.renderMaxZ = 1; + renderer.renderMinZ = 1.0 - width; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 1; + break; + case UP: + renderer.renderMaxY = 1; + renderer.renderMinY = 1.0 - width; + break; + case WEST: + renderer.renderMinX = 0; + renderer.renderMaxX = width; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 1; + renderer.uvRotateWest = 1; + renderer.uvRotateEast = 1; + break; + case UNKNOWN: + default: } i.renderBlockCurrentBounds( x, y, z, renderer ); @@ -327,18 +329,14 @@ public class RenderBlockCraftingCPU extends BaseBlockRender } } - private boolean isConnected(IBlockAccess w, int x, int y, int z, ForgeDirection side) + private float gso( ForgeDirection side, float def, ForgeDirection target ) { - final int tileYPos = y + side.offsetY; - if ( 0 <= tileYPos && tileYPos <= 255) + if( side != target ) { - final TileEntity tile = w.getTileEntity( x + side.offsetX, tileYPos, z + side.offsetZ ); - - return tile instanceof TileCraftingTile; - } - else - { - return false; + if( side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0 ) + return 16; + return 0; } + return def; } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java index 301b516d6..a68753efa 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java @@ -45,33 +45,34 @@ public class RenderBlockCraftingCPUMonitor extends RenderBlockCraftingCPU { private static final ReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; - public RenderBlockCraftingCPUMonitor() { + public RenderBlockCraftingCPUMonitor() + { super( true, 20 ); } @Override - public void renderTile(AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer) + public void renderTile( AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer ) { - if ( Platform.isDrawing( tess ) ) + if( Platform.isDrawing( tess ) ) return; - if ( tile instanceof TileCraftingMonitorTile ) + if( tile instanceof TileCraftingMonitorTile ) { TileCraftingMonitorTile cmt = (TileCraftingMonitorTile) tile; IAEItemStack ais = cmt.getJobProgress(); - if ( cmt.dspList == null ) + if( cmt.dspList == null ) { cmt.updateList = true; cmt.dspList = GLAllocation.generateDisplayLists( 1 ); } - if ( ais != null ) + if( ais != null ) { GL11.glPushMatrix(); GL11.glTranslated( x + 0.5, y + 0.5, z + 0.5 ); - if ( cmt.updateList ) + if( cmt.updateList ) { cmt.updateList = false; GL11.glNewList( cmt.dspList, GL11.GL_COMPILE_AND_EXECUTE ); @@ -86,7 +87,7 @@ public class RenderBlockCraftingCPUMonitor extends RenderBlockCraftingCPU } } - private void tesrRenderScreen(Tessellator tess, TileCraftingMonitorTile cmt, IAEItemStack ais) + private void tesrRenderScreen( Tessellator tess, TileCraftingMonitorTile cmt, IAEItemStack ais ) { ForgeDirection side = cmt.getForward(); @@ -94,7 +95,7 @@ public class RenderBlockCraftingCPUMonitor extends RenderBlockCraftingCPU int spin = 0; int max = 5; - while (walrus != cmt.getUp() && max > 0) + while( walrus != cmt.getUp() && max > 0 ) { max--; spin++; @@ -108,38 +109,38 @@ public class RenderBlockCraftingCPUMonitor extends RenderBlockCraftingCPU float scale = 0.7f; GL11.glScalef( scale, scale, scale ); - if ( side == ForgeDirection.UP ) + if( side == ForgeDirection.UP ) { GL11.glScalef( 1.0f, -1.0f, 1.0f ); GL11.glRotatef( 90.0f, 1.0f, 0.0f, 0.0f ); GL11.glRotatef( spin * 90.0F, 0, 0, 1 ); } - if ( side == ForgeDirection.DOWN ) + if( side == ForgeDirection.DOWN ) { GL11.glScalef( 1.0f, -1.0f, 1.0f ); GL11.glRotatef( -90.0f, 1.0f, 0.0f, 0.0f ); GL11.glRotatef( spin * -90.0F, 0, 0, 1 ); } - if ( side == ForgeDirection.EAST ) + if( side == ForgeDirection.EAST ) { GL11.glScalef( -1.0f, -1.0f, -1.0f ); GL11.glRotatef( -90.0f, 0.0f, 1.0f, 0.0f ); } - if ( side == ForgeDirection.WEST ) + if( side == ForgeDirection.WEST ) { GL11.glScalef( -1.0f, -1.0f, -1.0f ); GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); } - if ( side == ForgeDirection.NORTH ) + if( side == ForgeDirection.NORTH ) { GL11.glScalef( -1.0f, -1.0f, -1.0f ); } - if ( side == ForgeDirection.SOUTH ) + if( side == ForgeDirection.SOUTH ) { GL11.glScalef( -1.0f, -1.0f, -1.0f ); GL11.glRotatef( 180.0f, 0.0f, 1.0f, 0.0f ); @@ -164,9 +165,8 @@ public class RenderBlockCraftingCPUMonitor extends RenderBlockCraftingCPU tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); ClientHelper.proxy.doRenderItem( sis, cmt.getWorldObj() ); - } - catch (Exception e) + catch( Exception e ) { AELog.error( e ); } @@ -186,5 +186,4 @@ public class RenderBlockCraftingCPUMonitor extends RenderBlockCraftingCPU GL11.glPopAttrib(); } - } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java b/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java index 3e6abf146..931ca22ea 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; @@ -35,15 +36,17 @@ import appeng.client.render.BaseBlockRender; import appeng.tile.AEBaseTile; import appeng.tile.grindstone.TileCrank; + public class RenderBlockCrank extends BaseBlockRender { - public RenderBlockCrank() { + public RenderBlockCrank() + { super( true, 60 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { renderer.renderAllFaces = true; @@ -57,22 +60,22 @@ public class RenderBlockCrank extends BaseBlockRender } @Override - public boolean renderInWorld(AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { return true; } @Override - public void renderTile(AEBaseBlock blk, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderBlocks) + public void renderTile( AEBaseBlock blk, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderBlocks ) { TileCrank tc = (TileCrank) tile; - if ( tc.getUp() == null || tc.getUp() == ForgeDirection.UNKNOWN ) + if( tc.getUp() == null || tc.getUp() == ForgeDirection.UNKNOWN ) return; Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.locationBlocksTexture ); RenderHelper.disableStandardItemLighting(); - if ( Minecraft.isAmbientOcclusionEnabled() ) + if( Minecraft.isAmbientOcclusionEnabled() ) GL11.glShadeModel( GL11.GL_SMOOTH ); else GL11.glShadeModel( GL11.GL_FLAT ); @@ -102,5 +105,4 @@ public class RenderBlockCrank extends BaseBlockRender tess.setTranslation( 0, 0, 0 ); RenderHelper.enableStandardItemLighting(); } - } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java b/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java index 38a717b06..c2f7ee15c 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; @@ -27,25 +28,27 @@ import appeng.api.implementations.items.IAEItemPowerStorage; import appeng.block.AEBaseBlock; import appeng.client.render.BaseBlockRender; + public class RenderBlockEnergyCube extends BaseBlockRender { - public RenderBlockEnergyCube() { + public RenderBlockEnergyCube() + { super( false, 20 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { IAEItemPowerStorage myItem = (IAEItemPowerStorage) is.getItem(); double internalCurrentPower = myItem.getAECurrentPower( is ); double internalMaxPower = myItem.getAEMaxPower( is ); - int meta = (int) (8.0 * (internalCurrentPower / internalMaxPower)); + int meta = (int) ( 8.0 * ( internalCurrentPower / internalMaxPower ) ); - if ( meta > 7 ) + if( meta > 7 ) meta = 7; - if ( meta < 0 ) + if( meta < 0 ) meta = 0; renderer.setOverrideBlockTexture( blk.getIcon( 0, meta ) ); @@ -54,7 +57,7 @@ public class RenderBlockEnergyCube extends BaseBlockRender } @Override - public boolean renderInWorld(AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { int meta = world.getBlockMetadata( x, y, z ); diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java b/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java index f267058e8..92502d748 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import org.lwjgl.opengl.GL11; @@ -46,15 +47,17 @@ import appeng.tile.AEBaseTile; import appeng.tile.misc.TileInscriber; import appeng.util.Platform; + public class RenderBlockInscriber extends BaseBlockRender { - public RenderBlockInscriber() { + public RenderBlockInscriber() + { super( true, 30 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { Tessellator tess = Tessellator.instance; @@ -95,14 +98,15 @@ public class RenderBlockInscriber extends BaseBlockRender } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { this.preRenderInWorld( block, world, x, y, z, renderer ); BlockInscriber blk = (BlockInscriber) block; IOrientable te = this.getOrientable( block, world, x, y, z ); - if ( te == null ) return false; + if( te == null ) + return false; ForgeDirection fdy = te.getUp(); ForgeDirection fdz = te.getForward(); @@ -137,7 +141,7 @@ public class RenderBlockInscriber extends BaseBlockRender } @Override - public void renderTile(AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer) + public void renderTile( AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer ) { TileInscriber inv = (TileInscriber) tile; @@ -163,19 +167,19 @@ public class RenderBlockInscriber extends BaseBlockRender float base = 0.4f; long absoluteProgress = 0; - if ( inv.smash ) + if( inv.smash ) { long currentTime = System.currentTimeMillis(); absoluteProgress = currentTime - inv.clientStart; - if ( absoluteProgress > 800 ) + if( absoluteProgress > 800 ) inv.smash = false; } float relativeProgress = absoluteProgress % 800 / 400.0f; float progress = relativeProgress; - if ( progress > 1.0f ) - progress = 1.0f - (progress - 1.0f); + if( progress > 1.0f ) + progress = 1.0f - ( progress - 1.0f ); press -= progress / 5.0f; IIcon ic = ExtraBlockTextures.BlockInscriberInside.getIcon(); @@ -189,8 +193,8 @@ public class RenderBlockInscriber extends BaseBlockRender tess.addVertexWithUV( TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 ) ); tess.addVertexWithUV( 1.0 - TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle + base, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 - 16 * (press - base) ) ); - tess.addVertexWithUV( TwoPx, middle + base, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 - 16 * (press - base) ) ); + tess.addVertexWithUV( 1.0 - TwoPx, middle + base, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 - 16 * ( press - base ) ) ); + tess.addVertexWithUV( TwoPx, middle + base, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 - 16 * ( press - base ) ) ); middle -= 2.0f * 0.02f; tess.addVertexWithUV( 1.0 - TwoPx, middle - press, TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 2 ) ); @@ -200,29 +204,29 @@ public class RenderBlockInscriber extends BaseBlockRender tess.addVertexWithUV( 1.0 - TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 ) ); tess.addVertexWithUV( TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 ) ); - tess.addVertexWithUV( TwoPx, middle - base, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 - 16 * (press - base) ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle + -base, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 - 16 * (press - base) ) ); + tess.addVertexWithUV( TwoPx, middle - base, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 - 16 * ( press - base ) ) ); + tess.addVertexWithUV( 1.0 - TwoPx, middle + -base, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 - 16 * ( press - base ) ) ); tess.draw(); GL11.glPopMatrix(); int items = 0; - if ( inv.getStackInSlot( 0 ) != null ) + if( inv.getStackInSlot( 0 ) != null ) items++; - if ( inv.getStackInSlot( 1 ) != null ) + if( inv.getStackInSlot( 1 ) != null ) items++; - if ( inv.getStackInSlot( 2 ) != null ) + if( inv.getStackInSlot( 2 ) != null ) items++; - if ( relativeProgress > 1.0f || items == 0 ) + if( relativeProgress > 1.0f || items == 0 ) { ItemStack is = inv.getStackInSlot( 3 ); - if ( is == null ) + if( is == null ) { InscriberRecipe ir = inv.getTask(); - if ( ir != null ) + if( ir != null ) is = ir.output.copy(); } @@ -234,13 +238,11 @@ public class RenderBlockInscriber extends BaseBlockRender this.renderItem( inv.getStackInSlot( 1 ), -press, block, tile, tess, x, y, z, f, renderer ); this.renderItem( inv.getStackInSlot( 2 ), 0.0f, block, tile, tess, x, y, z, f, renderer ); } - } - public void renderItem(ItemStack sis, float o, AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, - RenderBlocks renderer) + public void renderItem( ItemStack sis, float o, AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer ) { - if ( sis != null ) + if( sis != null ) { sis = sis.copy(); GL11.glPushMatrix(); @@ -253,7 +255,7 @@ public class RenderBlockInscriber extends BaseBlockRender GL11.glScalef( 1.0f, 1.0f, 1.0f ); Block blk = Block.getBlockFromItem( sis.getItem() ); - if ( sis.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( blk.getRenderType() ) ) + if( sis.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( blk.getRenderType() ) ) { GL11.glRotatef( 25.0f, 1.0f, 0.0f, 0.0f ); GL11.glRotatef( 15.0f, 0.0f, 1.0f, 0.0f ); @@ -275,7 +277,7 @@ public class RenderBlockInscriber extends BaseBlockRender this.doRenderItem( sis, tile ); } - catch (Exception err) + catch( Exception err ) { AELog.error( err ); } @@ -283,5 +285,4 @@ public class RenderBlockInscriber extends BaseBlockRender GL11.glPopMatrix(); } } - } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java b/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java index 368aa53bb..7dbeb7df4 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; @@ -29,20 +30,22 @@ import appeng.client.render.BlockRenderInfo; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.misc.TileInterface; + public class RenderBlockInterface extends BaseBlockRender { - public RenderBlockInterface() { + public RenderBlockInterface() + { super( false, 20 ); } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { TileInterface ti = block.getTileEntity( world, x, y, z ); BlockRenderInfo info = block.getRendererInstance(); - if ( ti != null && ti.getForward() != ForgeDirection.UNKNOWN ) + if( ti != null && ti.getForward() != ForgeDirection.UNKNOWN ) { IIcon side = ExtraBlockTextures.BlockInterfaceAlternateArrow.getIcon(); info.setTemporaryRenderIcons( ExtraBlockTextures.BlockInterfaceAlternate.getIcon(), block.getIcon( 0, 0 ), side, side, side, side ); diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java b/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java index e7d397905..3fa38a798 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; @@ -34,25 +35,27 @@ import appeng.client.texture.ExtraBlockTextures; import appeng.helpers.Splotch; import appeng.tile.misc.TilePaint; + public class RenderBlockPaint extends BaseBlockRender { - public RenderBlockPaint() { + public RenderBlockPaint() + { super( false, 0 ); } @Override - public void renderInventory(AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { } @Override - public boolean renderInWorld(AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { TilePaint tp = imb.getTileEntity( world, x, y, z ); boolean out = false; - if ( tp != null ) + if( tp != null ) { // super.renderInWorld( imb, world, x, y, z, renderer ); @@ -67,18 +70,18 @@ public class RenderBlockPaint extends BaseBlockRender EnumSet validSides = EnumSet.noneOf( ForgeDirection.class ); - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) { - if ( tp.isSideValid( side ) ) + if( tp.isSideValid( side ) ) validSides.add( side ); } - for (Splotch s : tp.getDots()) + for( Splotch s : tp.getDots() ) { - if ( !validSides.contains( s.side ) ) + if( !validSides.contains( s.side ) ) continue; - if ( s.lumen ) + if( s.lumen ) { tess.setColorOpaque_I( s.color.whiteVariant ); tess.setBrightness( lumen ); @@ -100,13 +103,13 @@ public class RenderBlockPaint extends BaseBlockRender pos_x = Math.max( H, Math.min( 1.0 - H, pos_x ) ); pos_y = Math.max( H, Math.min( 1.0 - H, pos_y ) ); - if ( s.side == ForgeDirection.SOUTH || s.side == ForgeDirection.NORTH ) + if( s.side == ForgeDirection.SOUTH || s.side == ForgeDirection.NORTH ) { pos_x += x; pos_y += y; } - else if ( s.side == ForgeDirection.UP || s.side == ForgeDirection.DOWN ) + else if( s.side == ForgeDirection.UP || s.side == ForgeDirection.DOWN ) { pos_x += x; pos_y += z; @@ -120,54 +123,54 @@ public class RenderBlockPaint extends BaseBlockRender IIcon ico = icoSet[s.getSeed() % icoSet.length]; - switch (s.side) + switch( s.side ) { - case UP: - offset = 1.0 - offset; - tess.addVertexWithUV( pos_x - H, y + offset, pos_y - H, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + H, y + offset, pos_y - H, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + H, y + offset, pos_y + H, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x - H, y + offset, pos_y + H, ico.getMinU(), ico.getMaxV() ); - break; + case UP: + offset = 1.0 - offset; + tess.addVertexWithUV( pos_x - H, y + offset, pos_y - H, ico.getMinU(), ico.getMinV() ); + tess.addVertexWithUV( pos_x + H, y + offset, pos_y - H, ico.getMaxU(), ico.getMinV() ); + tess.addVertexWithUV( pos_x + H, y + offset, pos_y + H, ico.getMaxU(), ico.getMaxV() ); + tess.addVertexWithUV( pos_x - H, y + offset, pos_y + H, ico.getMinU(), ico.getMaxV() ); + break; - case DOWN: - tess.addVertexWithUV( pos_x + H, y + offset, pos_y - H, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - H, y + offset, pos_y - H, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - H, y + offset, pos_y + H, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x + H, y + offset, pos_y + H, ico.getMinU(), ico.getMaxV() ); - break; + case DOWN: + tess.addVertexWithUV( pos_x + H, y + offset, pos_y - H, ico.getMinU(), ico.getMinV() ); + tess.addVertexWithUV( pos_x - H, y + offset, pos_y - H, ico.getMaxU(), ico.getMinV() ); + tess.addVertexWithUV( pos_x - H, y + offset, pos_y + H, ico.getMaxU(), ico.getMaxV() ); + tess.addVertexWithUV( pos_x + H, y + offset, pos_y + H, ico.getMinU(), ico.getMaxV() ); + break; - case EAST: - offset = 1.0 - offset; - tess.addVertexWithUV( x + offset, pos_x + H, pos_y - H, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x - H, pos_y - H, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x - H, pos_y + H, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( x + offset, pos_x + H, pos_y + H, ico.getMinU(), ico.getMaxV() ); - break; + case EAST: + offset = 1.0 - offset; + tess.addVertexWithUV( x + offset, pos_x + H, pos_y - H, ico.getMinU(), ico.getMinV() ); + tess.addVertexWithUV( x + offset, pos_x - H, pos_y - H, ico.getMaxU(), ico.getMinV() ); + tess.addVertexWithUV( x + offset, pos_x - H, pos_y + H, ico.getMaxU(), ico.getMaxV() ); + tess.addVertexWithUV( x + offset, pos_x + H, pos_y + H, ico.getMinU(), ico.getMaxV() ); + break; - case WEST: - tess.addVertexWithUV( x + offset, pos_x - H, pos_y - H, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x + H, pos_y - H, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x + H, pos_y + H, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( x + offset, pos_x - H, pos_y + H, ico.getMinU(), ico.getMaxV() ); - break; + case WEST: + tess.addVertexWithUV( x + offset, pos_x - H, pos_y - H, ico.getMinU(), ico.getMinV() ); + tess.addVertexWithUV( x + offset, pos_x + H, pos_y - H, ico.getMaxU(), ico.getMinV() ); + tess.addVertexWithUV( x + offset, pos_x + H, pos_y + H, ico.getMaxU(), ico.getMaxV() ); + tess.addVertexWithUV( x + offset, pos_x - H, pos_y + H, ico.getMinU(), ico.getMaxV() ); + break; - case SOUTH: - offset = 1.0 - offset; - tess.addVertexWithUV( pos_x + H, pos_y - H, z + offset, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - H, pos_y - H, z + offset, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - H, pos_y + H, z + offset, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x + H, pos_y + H, z + offset, ico.getMinU(), ico.getMaxV() ); - break; + case SOUTH: + offset = 1.0 - offset; + tess.addVertexWithUV( pos_x + H, pos_y - H, z + offset, ico.getMinU(), ico.getMinV() ); + tess.addVertexWithUV( pos_x - H, pos_y - H, z + offset, ico.getMaxU(), ico.getMinV() ); + tess.addVertexWithUV( pos_x - H, pos_y + H, z + offset, ico.getMaxU(), ico.getMaxV() ); + tess.addVertexWithUV( pos_x + H, pos_y + H, z + offset, ico.getMinU(), ico.getMaxV() ); + break; - case NORTH: - tess.addVertexWithUV( pos_x - H, pos_y - H, z + offset, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + H, pos_y - H, z + offset, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + H, pos_y + H, z + offset, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x - H, pos_y + H, z + offset, ico.getMinU(), ico.getMaxV() ); - break; + case NORTH: + tess.addVertexWithUV( pos_x - H, pos_y - H, z + offset, ico.getMinU(), ico.getMinV() ); + tess.addVertexWithUV( pos_x + H, pos_y - H, z + offset, ico.getMaxU(), ico.getMinV() ); + tess.addVertexWithUV( pos_x + H, pos_y + H, z + offset, ico.getMaxU(), ico.getMaxV() ); + tess.addVertexWithUV( pos_x - H, pos_y + H, z + offset, ico.getMinU(), ico.getMaxV() ); + break; - default: + default: } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java b/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java index 5e03e392e..89f248fe3 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; @@ -28,20 +29,22 @@ import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.misc.TileQuartzGrowthAccelerator; + public class RenderBlockQuartzAccelerator extends BaseBlockRender { - public RenderBlockQuartzAccelerator() { + public RenderBlockQuartzAccelerator() + { super( false, 20 ); } @Override - public boolean renderInWorld(AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { TileEntity te = world.getTileEntity( x, y, z ); - if ( te instanceof TileQuartzGrowthAccelerator ) + if( te instanceof TileQuartzGrowthAccelerator ) { - if ( ((TileQuartzGrowthAccelerator) te).hasPower ) + if( ( (TileQuartzGrowthAccelerator) te ).hasPower ) { IIcon top_Bottom = ExtraBlockTextures.BlockQuartzGrowthAcceleratorOn.getIcon(); IIcon side = ExtraBlockTextures.BlockQuartzGrowthAcceleratorSideOn.getIcon(); diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java b/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java index a7d6d5ae3..4a10df5c6 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; @@ -34,23 +35,25 @@ import appeng.client.render.BaseBlockRender; import appeng.tile.AEBaseTile; import appeng.tile.storage.TileSkyChest; + public class RenderBlockSkyChest extends BaseBlockRender { final ModelChest model = new ModelChest(); - public RenderBlockSkyChest() { + public RenderBlockSkyChest() + { super( true, 80 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { - GL11.glEnable( 32826 /* GL_RESCALE_NORMAL_EXT */); + GL11.glEnable( 32826 /* GL_RESCALE_NORMAL_EXT */ ); GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); ResourceLocation loc; - if ( is.getItemDamage() == 1 ) + if( is.getItemDamage() == 1 ) loc = new ResourceLocation( "appliedenergistics2", "textures/models/skyblockchest.png" ); else loc = new ResourceLocation( "appliedenergistics2", "textures/models/skychest.png" ); @@ -62,37 +65,37 @@ public class RenderBlockSkyChest extends BaseBlockRender GL11.glScalef( 1.0F, -1F, -1F ); GL11.glTranslatef( -0.0F, -1.0F, -1.0F ); - this.model.chestLid.offsetY = -(0.9f / 16.0f); - this.model.chestLid.rotateAngleX = -((lidAngle * 3.141593F) / 2.0F); + this.model.chestLid.offsetY = -( 0.9f / 16.0f ); + this.model.chestLid.rotateAngleX = -( ( lidAngle * 3.141593F ) / 2.0F ); this.model.renderAll(); - GL11.glDisable( 32826 /* GL_RESCALE_NORMAL_EXT */); + GL11.glDisable( 32826 /* GL_RESCALE_NORMAL_EXT */ ); GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); } @Override - public boolean renderInWorld(AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { return true; } @Override - public void renderTile(AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float partialTick, RenderBlocks renderer) + public void renderTile( AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float partialTick, RenderBlocks renderer ) { - if ( !(tile instanceof TileSkyChest) ) + if( !( tile instanceof TileSkyChest ) ) return; TileSkyChest skyChest = (TileSkyChest) tile; - if ( !skyChest.hasWorldObj() ) + if( !skyChest.hasWorldObj() ) return; - GL11.glEnable( 32826 /* GL_RESCALE_NORMAL_EXT */); + GL11.glEnable( 32826 /* GL_RESCALE_NORMAL_EXT */ ); GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); ResourceLocation loc; - if ( tile.getWorldObj().getBlockMetadata( tile.xCoord, tile.yCoord, tile.zCoord ) == 1 ) + if( tile.getWorldObj().getBlockMetadata( tile.xCoord, tile.yCoord, tile.zCoord ) == 1 ) loc = new ResourceLocation( "appliedenergistics2", "textures/models/skyblockchest.png" ); else loc = new ResourceLocation( "appliedenergistics2", "textures/models/skychest.png" ); @@ -107,26 +110,26 @@ public class RenderBlockSkyChest extends BaseBlockRender long now = System.currentTimeMillis(); long distance = now - skyChest.lastEvent; - if ( skyChest.playerOpen > 0 ) + if( skyChest.playerOpen > 0 ) skyChest.lidAngle += distance * 0.0001; else skyChest.lidAngle -= distance * 0.0001; - if ( skyChest.lidAngle > 0.5f ) + if( skyChest.lidAngle > 0.5f ) skyChest.lidAngle = 0.5f; - if ( skyChest.lidAngle < 0.0f ) + if( skyChest.lidAngle < 0.0f ) skyChest.lidAngle = 0.0f; float lidAngle = skyChest.lidAngle; lidAngle = 1.0F - lidAngle; lidAngle = 1.0F - lidAngle * lidAngle * lidAngle; - this.model.chestLid.offsetY = -(1.01f / 16.0f); - this.model.chestLid.rotateAngleX = -((lidAngle * 3.141593F) / 2.0F); + this.model.chestLid.offsetY = -( 1.01f / 16.0f ); + this.model.chestLid.rotateAngleX = -( ( lidAngle * 3.141593F ) / 2.0F ); this.model.renderAll(); - GL11.glDisable( 32826 /* GL_RESCALE_NORMAL_EXT */); + GL11.glDisable( 32826 /* GL_RESCALE_NORMAL_EXT */ ); GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java b/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java index b64facd60..1d3195a9b 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; @@ -39,40 +40,42 @@ import appeng.hooks.CompassResult; import appeng.tile.AEBaseTile; import appeng.tile.misc.TileSkyCompass; + public class RenderBlockSkyCompass extends BaseBlockRender { - float r = 0; final ModelCompass model = new ModelCompass(); + float r = 0; - public RenderBlockSkyCompass() { + public RenderBlockSkyCompass() + { super( true, 80 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { - if ( type == ItemRenderType.INVENTORY ) + if( type == ItemRenderType.INVENTORY ) { boolean isGood = false; IInventory inv = Minecraft.getMinecraft().thePlayer.inventory; - for (int x = 0; x < inv.getSizeInventory(); x++) - if ( inv.getStackInSlot( x ) == is ) + for( int x = 0; x < inv.getSizeInventory(); x++ ) + if( inv.getStackInSlot( x ) == is ) isGood = true; - if ( !isGood ) + if( !isGood ) type = ItemRenderType.FIRST_PERSON_MAP; } - GL11.glEnable( 32826 /* GL_RESCALE_NORMAL_EXT */); + GL11.glEnable( 32826 /* GL_RESCALE_NORMAL_EXT */ ); GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); ResourceLocation loc = new ResourceLocation( "appliedenergistics2", "textures/models/compass.png" ); Minecraft.getMinecraft().getTextureManager().bindTexture( loc ); - if ( type == ItemRenderType.ENTITY ) + if( type == ItemRenderType.ENTITY ) { GL11.glRotatef( -90.0f, 0.0f, 0.0f, 1.0f ); GL11.glScalef( 1.0F, -1F, -1F ); @@ -81,25 +84,25 @@ public class RenderBlockSkyCompass extends BaseBlockRender } else { - if ( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) + if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) GL11.glRotatef( 15.3f, 0.0f, 0.0f, 1.0f ); GL11.glScalef( 1.0F, -1F, -1F ); GL11.glScalef( 2.5f, 2.5f, 2.5f ); - if ( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) + if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) GL11.glTranslatef( 0.3F, -1.65F, -0.19F ); else GL11.glTranslatef( 0.2F, -1.65F, -0.19F ); } long now = System.currentTimeMillis(); - if ( type == ItemRenderType.EQUIPPED_FIRST_PERSON || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED ) + if( type == ItemRenderType.EQUIPPED_FIRST_PERSON || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED ) { EntityPlayer p = Minecraft.getMinecraft().thePlayer; float rYaw = p.rotationYaw; - if ( type == ItemRenderType.EQUIPPED ) + if( type == ItemRenderType.EQUIPPED ) { p = (EntityPlayer) obj[1]; rYaw = p.renderYawOffset; @@ -110,20 +113,20 @@ public class RenderBlockSkyCompass extends BaseBlockRender int z = (int) p.posZ; CompassResult cr = CompassManager.INSTANCE.getCompassDirection( 0, x, y, z ); - for (int i = 0; i < 3; i++) - for (int j = 0; j < 3; j++) + for( int i = 0; i < 3; i++ ) + for( int j = 0; j < 3; j++ ) CompassManager.INSTANCE.getCompassDirection( 0, x + i - 1, y, z + j - 1 ); - if ( cr.hasResult ) + if( cr.hasResult ) { - if ( cr.spin ) + if( cr.spin ) { now %= 100000; - this.model.renderAll( (now / 50000.0f) * (float) Math.PI * 500.0f ); + this.model.renderAll( ( now / 50000.0f ) * (float) Math.PI * 500.0f ); } else { - if ( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) + if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) { float offRads = rYaw / 180.0f * (float) Math.PI; float adjustment = (float) Math.PI * 0.74f; @@ -140,38 +143,37 @@ public class RenderBlockSkyCompass extends BaseBlockRender else { now %= 1000000; - this.model.renderAll( (now / 500000.0f) * (float) Math.PI * 500.0f ); + this.model.renderAll( ( now / 500000.0f ) * (float) Math.PI * 500.0f ); } - } else { now %= 100000; - this.model.renderAll( (now / 50000.0f) * (float) Math.PI * 500.0f ); + this.model.renderAll( ( now / 50000.0f ) * (float) Math.PI * 500.0f ); } - GL11.glDisable( 32826 /* GL_RESCALE_NORMAL_EXT */); + GL11.glDisable( 32826 /* GL_RESCALE_NORMAL_EXT */ ); GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); } @Override - public boolean renderInWorld(AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { return true; } @Override - public void renderTile(AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float partialTick, RenderBlocks renderer) + public void renderTile( AEBaseBlock block, AEBaseTile tile, Tessellator tess, double x, double y, double z, float partialTick, RenderBlocks renderer ) { - if ( !(tile instanceof TileSkyCompass) ) + if( !( tile instanceof TileSkyCompass ) ) return; TileSkyCompass skyCompass = (TileSkyCompass) tile; - if ( !skyCompass.hasWorldObj() ) + if( !skyCompass.hasWorldObj() ) return; - GL11.glEnable( 32826 /* GL_RESCALE_NORMAL_EXT */); + GL11.glEnable( 32826 /* GL_RESCALE_NORMAL_EXT */ ); GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); ResourceLocation loc = new ResourceLocation( "appliedenergistics2", "textures/models/compass.png" ); @@ -186,33 +188,32 @@ public class RenderBlockSkyCompass extends BaseBlockRender long now = System.currentTimeMillis(); CompassResult cr = null; - if ( skyCompass.getForward() == ForgeDirection.UP || skyCompass.getForward() == ForgeDirection.DOWN ) + if( skyCompass.getForward() == ForgeDirection.UP || skyCompass.getForward() == ForgeDirection.DOWN ) cr = CompassManager.INSTANCE.getCompassDirection( 0, tile.xCoord, tile.yCoord, tile.zCoord ); else cr = new CompassResult( false, true, 0 ); - if ( cr.hasResult ) + if( cr.hasResult ) { - if ( cr.spin ) + if( cr.spin ) { now %= 100000; - this.model.renderAll( (now / 50000.0f) * (float) Math.PI * 500.0f ); + this.model.renderAll( ( now / 50000.0f ) * (float) Math.PI * 500.0f ); } else - this.model.renderAll( (float) (skyCompass.getForward() == ForgeDirection.DOWN ? this.flipidiy( cr.rad ) : cr.rad) ); - + this.model.renderAll( (float) ( skyCompass.getForward() == ForgeDirection.DOWN ? this.flipidiy( cr.rad ) : cr.rad ) ); } else { now %= 1000000; - this.model.renderAll( (now / 500000.0f) * (float) Math.PI * 500.0f ); + this.model.renderAll( ( now / 500000.0f ) * (float) Math.PI * 500.0f ); } - GL11.glDisable( 32826 /* GL_RESCALE_NORMAL_EXT */); + GL11.glDisable( 32826 /* GL_RESCALE_NORMAL_EXT */ ); GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); } - private double flipidiy(double rad) + private double flipidiy( double rad ) { double x = Math.cos( rad ); double y = Math.sin( rad ); diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java b/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java index 237c44502..408d35f01 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; @@ -38,15 +39,24 @@ import appeng.client.texture.OffsetIcon; import appeng.tile.networking.TileWireless; import appeng.util.Platform; + public class RenderBlockWireless extends BaseBlockRender { - public RenderBlockWireless() { + int centerX = 0; + int centerY = 0; + int centerZ = 0; + AEBaseBlock blk; + boolean hasChan = false; + boolean hasPower = false; + + public RenderBlockWireless() + { super( false, 20 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { this.blk = blk; this.centerX = 0; @@ -81,43 +91,30 @@ public class RenderBlockWireless extends BaseBlockRender int s = 1; - for (ForgeDirection side : sides) + for( ForgeDirection side : sides ) { - this.renderBlockBounds( renderer, 8 + (side.offsetX != 0 ? side.offsetX * 2 : -2), 8 + (side.offsetY != 0 ? side.offsetY * 2 : -2), 2 - + (side.offsetZ != 0 ? side.offsetZ * 2 : -1) + s, 8 + (side.offsetX != 0 ? side.offsetX * 4 : 2), - 8 + (side.offsetY != 0 ? side.offsetY * 4 : 2), 2 + (side.offsetZ != 0 ? side.offsetZ * 5 : 1) + s, ForgeDirection.EAST, ForgeDirection.UP, - ForgeDirection.SOUTH ); + this.renderBlockBounds( renderer, 8 + ( side.offsetX != 0 ? side.offsetX * 2 : -2 ), 8 + ( side.offsetY != 0 ? side.offsetY * 2 : -2 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 2 : -1 ) + s, 8 + ( side.offsetX != 0 ? side.offsetX * 4 : 2 ), 8 + ( side.offsetY != 0 ? side.offsetY * 4 : 2 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 5 : 1 ) + s, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); } s = 3; - for (ForgeDirection side : sides) + for( ForgeDirection side : sides ) { - this.renderBlockBounds( renderer, 8 + (side.offsetX != 0 ? side.offsetX * 4 : -1), 8 + (side.offsetY != 0 ? side.offsetY * 4 : -1), 1 - + (side.offsetZ != 0 ? side.offsetZ * 4 : -1) + s, 8 + (side.offsetX != 0 ? side.offsetX * 5 : 1), - 8 + (side.offsetY != 0 ? side.offsetY * 5 : 1), 2 + (side.offsetZ != 0 ? side.offsetZ * 5 : 1) + s, ForgeDirection.EAST, ForgeDirection.UP, - ForgeDirection.SOUTH ); + this.renderBlockBounds( renderer, 8 + ( side.offsetX != 0 ? side.offsetX * 4 : -1 ), 8 + ( side.offsetY != 0 ? side.offsetY * 4 : -1 ), 1 + ( side.offsetZ != 0 ? side.offsetZ * 4 : -1 ) + s, 8 + ( side.offsetX != 0 ? side.offsetX * 5 : 1 ), 8 + ( side.offsetY != 0 ? side.offsetY * 5 : 1 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 5 : 1 ) + s, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); } } - int centerX = 0; - int centerY = 0; - int centerZ = 0; - AEBaseBlock blk; - boolean hasChan = false; - boolean hasPower = false; - @Override - public boolean renderInWorld(AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { TileWireless tw = blk.getTileEntity( world, x, y, z ); this.blk = blk; - if ( tw != null ) + if( tw != null ) { - this.hasChan = (tw.clientFlags & (TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG)) == (TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG); - this.hasPower = (tw.clientFlags & TileWireless.POWERED_FLAG) == TileWireless.POWERED_FLAG; + this.hasChan = ( tw.clientFlags & ( TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG ) ) == ( TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG ); + this.hasPower = ( tw.clientFlags & TileWireless.POWERED_FLAG ) == TileWireless.POWERED_FLAG; BlockRenderInfo ri = blk.getRendererInstance(); @@ -151,20 +148,16 @@ public class RenderBlockWireless extends BaseBlockRender int s = 1; - for (ForgeDirection side : sides) + for( ForgeDirection side : sides ) { - this.renderBlockBounds( renderer, 8 + (side.offsetX != 0 ? side.offsetX * 2 : -2), 8 + (side.offsetY != 0 ? side.offsetY * 2 : -2), 2 - + (side.offsetZ != 0 ? side.offsetZ * 2 : -1) + s, 8 + (side.offsetX != 0 ? side.offsetX * 4 : 2), - 8 + (side.offsetY != 0 ? side.offsetY * 4 : 2), 2 + (side.offsetZ != 0 ? side.offsetZ * 5 : 1) + s, fdx, fdy, fdz ); + this.renderBlockBounds( renderer, 8 + ( side.offsetX != 0 ? side.offsetX * 2 : -2 ), 8 + ( side.offsetY != 0 ? side.offsetY * 2 : -2 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 2 : -1 ) + s, 8 + ( side.offsetX != 0 ? side.offsetX * 4 : 2 ), 8 + ( side.offsetY != 0 ? side.offsetY * 4 : 2 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 5 : 1 ) + s, fdx, fdy, fdz ); super.renderInWorld( blk, world, x, y, z, renderer ); } s = 3; - for (ForgeDirection side : sides) + for( ForgeDirection side : sides ) { - this.renderBlockBounds( renderer, 8 + (side.offsetX != 0 ? side.offsetX * 4 : -1), 8 + (side.offsetY != 0 ? side.offsetY * 4 : -1), 1 - + (side.offsetZ != 0 ? side.offsetZ * 4 : -1) + s, 8 + (side.offsetX != 0 ? side.offsetX * 5 : 1), - 8 + (side.offsetY != 0 ? side.offsetY * 5 : 1), 2 + (side.offsetZ != 0 ? side.offsetZ * 5 : 1) + s, fdx, fdy, fdz ); + this.renderBlockBounds( renderer, 8 + ( side.offsetX != 0 ? side.offsetX * 4 : -1 ), 8 + ( side.offsetY != 0 ? side.offsetY * 4 : -1 ), 1 + ( side.offsetZ != 0 ? side.offsetZ * 4 : -1 ) + s, 8 + ( side.offsetX != 0 ? side.offsetX * 5 : 1 ), 8 + ( side.offsetY != 0 ? side.offsetY * 5 : 1 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 5 : 1 ) + s, fdx, fdy, fdz ); super.renderInWorld( blk, world, x, y, z, renderer ); } @@ -173,13 +166,13 @@ public class RenderBlockWireless extends BaseBlockRender // ExtraTextures.BlockChargerInside.getIcon(), r, r ); this.renderBlockBounds( renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz ); - if ( this.hasChan ) + if( this.hasChan ) { int l = 14; Tessellator.instance.setBrightness( l << 20 | l << 4 ); Tessellator.instance.setColorOpaque_I( AEColor.Transparent.blackVariant ); } - else if ( this.hasPower ) + else if( this.hasPower ) { int l = 9; Tessellator.instance.setBrightness( l << 20 | l << 4 ); @@ -191,17 +184,17 @@ public class RenderBlockWireless extends BaseBlockRender Tessellator.instance.setColorOpaque_I( 0x000000 ); } - if ( ForgeDirection.UP != fdz.getOpposite() ) + if( ForgeDirection.UP != fdz.getOpposite() ) super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.UP ); - if ( ForgeDirection.DOWN != fdz.getOpposite() ) + if( ForgeDirection.DOWN != fdz.getOpposite() ) super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.DOWN ); - if ( ForgeDirection.EAST != fdz.getOpposite() ) + if( ForgeDirection.EAST != fdz.getOpposite() ) super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.EAST ); - if ( ForgeDirection.WEST != fdz.getOpposite() ) + if( ForgeDirection.WEST != fdz.getOpposite() ) super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.WEST ); - if ( ForgeDirection.SOUTH != fdz.getOpposite() ) + if( ForgeDirection.SOUTH != fdz.getOpposite() ) super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.SOUTH ); - if ( ForgeDirection.NORTH != fdz.getOpposite() ) + if( ForgeDirection.NORTH != fdz.getOpposite() ) super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.NORTH ); ri.setTemporaryRenderIcon( null ); @@ -211,45 +204,45 @@ public class RenderBlockWireless extends BaseBlockRender return true; } - private void renderTorchAtAngle(RenderBlocks renderer, ForgeDirection x, ForgeDirection y, ForgeDirection z) + private void renderTorchAtAngle( RenderBlocks renderer, ForgeDirection x, ForgeDirection y, ForgeDirection z ) { - IIcon r = (this.hasChan ? CableBusTextures.BlockWirelessOn.getIcon() : this.blk.getIcon( 0, 0 )); + IIcon r = ( this.hasChan ? CableBusTextures.BlockWirelessOn.getIcon() : this.blk.getIcon( 0, 0 ) ); IIcon sides = new OffsetIcon( r, 0.0f, -2.0f ); - switch (z) + switch( z ) { - case DOWN: - renderer.uvRotateNorth = 3; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; - renderer.uvRotateWest = 3; - break; - case EAST: - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - break; - case NORTH: - renderer.uvRotateTop = 0; - renderer.uvRotateBottom = 0; - renderer.uvRotateNorth = 2; - renderer.uvRotateSouth = 1; - break; - case SOUTH: - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - break; - case WEST: - renderer.uvRotateTop = 2; - renderer.uvRotateBottom = 1; - renderer.uvRotateEast = 1; - renderer.uvRotateWest = 2; - break; - default: - break; + case DOWN: + renderer.uvRotateNorth = 3; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; + renderer.uvRotateWest = 3; + break; + case EAST: + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + break; + case NORTH: + renderer.uvRotateTop = 0; + renderer.uvRotateBottom = 0; + renderer.uvRotateNorth = 2; + renderer.uvRotateSouth = 1; + break; + case SOUTH: + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + break; + case WEST: + renderer.uvRotateTop = 2; + renderer.uvRotateBottom = 1; + renderer.uvRotateEast = 1; + renderer.uvRotateWest = 2; + break; + default: + break; } Tessellator.instance.setColorOpaque_I( 0xffffff ); diff --git a/src/main/java/appeng/client/render/blocks/RenderDrive.java b/src/main/java/appeng/client/render/blocks/RenderDrive.java index 8c1a9ee60..63924a54e 100644 --- a/src/main/java/appeng/client/render/blocks/RenderDrive.java +++ b/src/main/java/appeng/client/render/blocks/RenderDrive.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; @@ -34,15 +35,17 @@ import appeng.client.texture.ExtraBlockTextures; import appeng.tile.storage.TileDrive; import appeng.util.Platform; + public class RenderDrive extends BaseBlockRender { - public RenderDrive() { + public RenderDrive() + { super( false, 0 ); } @Override - public void renderInventory(AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); @@ -52,7 +55,7 @@ public class RenderDrive extends BaseBlockRender } @Override - public boolean renderInWorld(AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { TileDrive sp = imb.getTileEntity( world, x, y, z ); renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); @@ -68,219 +71,149 @@ public class RenderDrive extends BaseBlockRender int b = world.getLightBrightnessForSkyBlocks( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0 ); - for (int yy = 0; yy < 5; yy++) + for( int yy = 0; yy < 5; yy++ ) { - for (int xx = 0; xx < 2; xx++) + for( int xx = 0; xx < 2; xx++ ) { - int stat = sp.getCellStatus( yy * 2 + (1 - xx) ); + int stat = sp.getCellStatus( yy * 2 + ( 1 - xx ) ); this.selectFace( renderer, west, up, forward, 2 + xx * 7, 7 + xx * 7, 1 + yy * 3, 3 + yy * 3 ); int spin = 0; - switch (forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3) + switch( forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3 ) { - case 1: - switch (up) - { - case UP: - spin = 3; + case 1: + switch( up ) + { + case UP: + spin = 3; + break; + case DOWN: + spin = 1; + break; + case NORTH: + spin = 0; + break; + case SOUTH: + spin = 2; + break; + default: + } break; - case DOWN: - spin = 1; + case -1: + switch( up ) + { + case UP: + spin = 1; + break; + case DOWN: + spin = 3; + break; + case NORTH: + spin = 0; + break; + case SOUTH: + spin = 2; + break; + default: + } break; - case NORTH: - spin = 0; + case -2: + switch( up ) + { + case EAST: + spin = 1; + break; + case WEST: + spin = 3; + break; + case NORTH: + spin = 2; + break; + case SOUTH: + spin = 0; + break; + default: + } break; - case SOUTH: - spin = 2; + case 2: + switch( up ) + { + case EAST: + spin = 1; + break; + case WEST: + spin = 3; + break; + case NORTH: + spin = 0; + break; + case SOUTH: + spin = 0; + break; + default: + } break; - default: - } - break; - case -1: - switch (up) - { - case UP: - spin = 1; + case 3: + switch( up ) + { + case UP: + spin = 2; + break; + case DOWN: + spin = 0; + break; + case EAST: + spin = 3; + break; + case WEST: + spin = 1; + break; + default: + } break; - case DOWN: - spin = 3; + case -3: + switch( up ) + { + case UP: + spin = 2; + break; + case DOWN: + spin = 0; + break; + case EAST: + spin = 1; + break; + case WEST: + spin = 3; + break; + default: + } break; - case NORTH: - spin = 0; - break; - case SOUTH: - spin = 2; - break; - default: - } - break; - case -2: - switch (up) - { - case EAST: - spin = 1; - break; - case WEST: - spin = 3; - break; - case NORTH: - spin = 2; - break; - case SOUTH: - spin = 0; - break; - default: - } - break; - case 2: - switch (up) - { - case EAST: - spin = 1; - break; - case WEST: - spin = 3; - break; - case NORTH: - spin = 0; - break; - case SOUTH: - spin = 0; - break; - default: - } - break; - case 3: - switch (up) - { - case UP: - spin = 2; - break; - case DOWN: - spin = 0; - break; - case EAST: - spin = 3; - break; - case WEST: - spin = 1; - break; - default: - } - break; - case -3: - switch (up) - { - case UP: - spin = 2; - break; - case DOWN: - spin = 0; - break; - case EAST: - spin = 1; - break; - case WEST: - spin = 3; - break; - default: - } - break; } - double u1 = ico.getInterpolatedU( (spin % 4 < 2) ? 1 : 6 ); - double u2 = ico.getInterpolatedU( ((spin + 1) % 4 < 2) ? 1 : 6 ); - double u3 = ico.getInterpolatedU( ((spin + 2) % 4 < 2) ? 1 : 6 ); - double u4 = ico.getInterpolatedU( ((spin + 3) % 4 < 2) ? 1 : 6 ); + double u1 = ico.getInterpolatedU( ( spin % 4 < 2 ) ? 1 : 6 ); + double u2 = ico.getInterpolatedU( ( ( spin + 1 ) % 4 < 2 ) ? 1 : 6 ); + double u3 = ico.getInterpolatedU( ( ( spin + 2 ) % 4 < 2 ) ? 1 : 6 ); + double u4 = ico.getInterpolatedU( ( ( spin + 3 ) % 4 < 2 ) ? 1 : 6 ); int m = 1; int mx = 3; - if ( stat == 0 ) + if( stat == 0 ) { m = 4; mx = 5; } - double v1 = ico.getInterpolatedV( ((spin + 1) % 4 < 2) ? m : mx ); - double v2 = ico.getInterpolatedV( ((spin + 2) % 4 < 2) ? m : mx ); - double v3 = ico.getInterpolatedV( ((spin + 3) % 4 < 2) ? m : mx ); - double v4 = ico.getInterpolatedV( ((spin) % 4 < 2) ? m : mx ); + double v1 = ico.getInterpolatedV( ( ( spin + 1 ) % 4 < 2 ) ? m : mx ); + double v2 = ico.getInterpolatedV( ( ( spin + 2 ) % 4 < 2 ) ? m : mx ); + double v3 = ico.getInterpolatedV( ( ( spin + 3 ) % 4 < 2 ) ? m : mx ); + double v4 = ico.getInterpolatedV( ( ( spin ) % 4 < 2 ) ? m : mx ); tess.setBrightness( b ); tess.setColorOpaque_I( 0xffffff ); - switch (forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3) + switch( forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3 ) { - case 1: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u4, v4 ); - break; - case -1: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case -2: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case 2: - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case 3: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); - break; - case -3: - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); - break; - } - - if ( (forward == ForgeDirection.UP && up == ForgeDirection.SOUTH) || forward == ForgeDirection.DOWN ) - this.selectFace( renderer, west, up, forward, 3 + xx * 7, 4 + xx * 7, 1 + yy * 3, 2 + yy * 3 ); - else - this.selectFace( renderer, west, up, forward, 5 + xx * 7, 6 + xx * 7, 2 + yy * 3, 3 + yy * 3 ); - - if ( stat != 0 ) - { - IIcon whiteIcon = ExtraBlockTextures.White.getIcon(); - u1 = whiteIcon.getInterpolatedU( (spin % 4 < 2) ? 1 : 6 ); - u2 = whiteIcon.getInterpolatedU( ((spin + 1) % 4 < 2) ? 1 : 6 ); - u3 = whiteIcon.getInterpolatedU( ((spin + 2) % 4 < 2) ? 1 : 6 ); - u4 = whiteIcon.getInterpolatedU( ((spin + 3) % 4 < 2) ? 1 : 6 ); - - v1 = whiteIcon.getInterpolatedV( ((spin + 1) % 4 < 2) ? 1 : 3 ); - v2 = whiteIcon.getInterpolatedV( ((spin + 2) % 4 < 2) ? 1 : 3 ); - v3 = whiteIcon.getInterpolatedV( ((spin + 3) % 4 < 2) ? 1 : 3 ); - v4 = whiteIcon.getInterpolatedV( ((spin) % 4 < 2) ? 1 : 3 ); - - if ( sp.isPowered() ) - tess.setBrightness( 15 << 20 | 15 << 4 ); - else - tess.setBrightness( 0 ); - - if ( stat == 1 ) - Tessellator.instance.setColorOpaque_I( 0x00ff00 ); - if ( stat == 2 ) - Tessellator.instance.setColorOpaque_I( 0xffaa00 ); - if ( stat == 3 ) - Tessellator.instance.setColorOpaque_I( 0xff0000 ); - - switch (forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3) - { case 1: tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); @@ -317,6 +250,76 @@ public class RenderDrive extends BaseBlockRender tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); break; + } + + if( ( forward == ForgeDirection.UP && up == ForgeDirection.SOUTH ) || forward == ForgeDirection.DOWN ) + this.selectFace( renderer, west, up, forward, 3 + xx * 7, 4 + xx * 7, 1 + yy * 3, 2 + yy * 3 ); + else + this.selectFace( renderer, west, up, forward, 5 + xx * 7, 6 + xx * 7, 2 + yy * 3, 3 + yy * 3 ); + + if( stat != 0 ) + { + IIcon whiteIcon = ExtraBlockTextures.White.getIcon(); + u1 = whiteIcon.getInterpolatedU( ( spin % 4 < 2 ) ? 1 : 6 ); + u2 = whiteIcon.getInterpolatedU( ( ( spin + 1 ) % 4 < 2 ) ? 1 : 6 ); + u3 = whiteIcon.getInterpolatedU( ( ( spin + 2 ) % 4 < 2 ) ? 1 : 6 ); + u4 = whiteIcon.getInterpolatedU( ( ( spin + 3 ) % 4 < 2 ) ? 1 : 6 ); + + v1 = whiteIcon.getInterpolatedV( ( ( spin + 1 ) % 4 < 2 ) ? 1 : 3 ); + v2 = whiteIcon.getInterpolatedV( ( ( spin + 2 ) % 4 < 2 ) ? 1 : 3 ); + v3 = whiteIcon.getInterpolatedV( ( ( spin + 3 ) % 4 < 2 ) ? 1 : 3 ); + v4 = whiteIcon.getInterpolatedV( ( ( spin ) % 4 < 2 ) ? 1 : 3 ); + + if( sp.isPowered() ) + tess.setBrightness( 15 << 20 | 15 << 4 ); + else + tess.setBrightness( 0 ); + + if( stat == 1 ) + Tessellator.instance.setColorOpaque_I( 0x00ff00 ); + if( stat == 2 ) + Tessellator.instance.setColorOpaque_I( 0xffaa00 ); + if( stat == 3 ) + Tessellator.instance.setColorOpaque_I( 0xff0000 ); + + switch( forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3 ) + { + case 1: + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u3, v3 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u4, v4 ); + break; + case -1: + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u1, v1 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u2, v2 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); + break; + case -2: + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); + tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); + tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); + break; + case 2: + tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); + tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); + break; + case 3: + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); + tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); + tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); + break; + case -3: + tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1 ); + tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); + tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); + break; } } } diff --git a/src/main/java/appeng/client/render/blocks/RenderMEChest.java b/src/main/java/appeng/client/render/blocks/RenderMEChest.java index eb29f26cb..10dea7ecc 100644 --- a/src/main/java/appeng/client/render/blocks/RenderMEChest.java +++ b/src/main/java/appeng/client/render/blocks/RenderMEChest.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; @@ -39,35 +40,37 @@ import appeng.client.texture.OffsetIcon; import appeng.tile.storage.TileChest; import appeng.util.Platform; + public class RenderMEChest extends BaseBlockRender { - public RenderMEChest() { + public RenderMEChest() + { super( false, 0 ); } @Override - public void renderInventory(AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { Tessellator.instance.setBrightness( 0 ); renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); - this.renderInvBlock( EnumSet.of( ForgeDirection.UP ), block, is, Tessellator.instance, this.adjustBrightness( AEColor.Transparent.whiteVariant, 0.7 ), - renderer ); + this.renderInvBlock( EnumSet.of( ForgeDirection.UP ), block, is, Tessellator.instance, this.adjustBrightness( AEColor.Transparent.whiteVariant, 0.7 ), renderer ); renderer.overrideBlockTexture = null; super.renderInventory( block, is, renderer, type, obj ); } @Override - public boolean renderInWorld(AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { TileChest sp = imb.getTileEntity( world, x, y, z ); renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); - if ( sp == null ) return false; + if( sp == null ) + return false; ForgeDirection up = sp.getUp(); ForgeDirection forward = sp.getForward(); @@ -82,7 +85,7 @@ public class RenderMEChest extends BaseBlockRender int offsetU = -4; int offsetV = 8; - if ( stat == 0 ) + if( stat == 0 ) offsetV = 3; int b = world.getLightBrightnessForSkyBlocks( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0 ); @@ -90,15 +93,15 @@ public class RenderMEChest extends BaseBlockRender Tessellator.instance.setColorOpaque_I( 0xffffff ); FlippableIcon flippableIcon = new FlippableIcon( new OffsetIcon( ExtraBlockTextures.MEStorageCellTextures.getIcon(), offsetU, offsetV ) ); - if ( forward == ForgeDirection.EAST && (up == ForgeDirection.NORTH || up == ForgeDirection.SOUTH) ) + if( forward == ForgeDirection.EAST && ( up == ForgeDirection.NORTH || up == ForgeDirection.SOUTH ) ) flippableIcon.setFlip( true, false ); - else if ( forward == ForgeDirection.NORTH && up == ForgeDirection.EAST ) + else if( forward == ForgeDirection.NORTH && up == ForgeDirection.EAST ) flippableIcon.setFlip( false, true ); - else if ( forward == ForgeDirection.NORTH && up == ForgeDirection.WEST ) + else if( forward == ForgeDirection.NORTH && up == ForgeDirection.WEST ) flippableIcon.setFlip( true, false ); - else if ( forward == ForgeDirection.DOWN && up == ForgeDirection.EAST ) + else if( forward == ForgeDirection.DOWN && up == ForgeDirection.EAST ) flippableIcon.setFlip( false, true ); - else if ( forward == ForgeDirection.DOWN ) + else if( forward == ForgeDirection.DOWN ) flippableIcon.setFlip( true, false ); /* @@ -110,27 +113,27 @@ public class RenderMEChest extends BaseBlockRender this.renderFace( x, y, z, imb, flippableIcon, renderer, forward ); - if ( stat != 0 ) + if( stat != 0 ) { b = 0; - if ( sp.isPowered() ) + if( sp.isPowered() ) { b = 15 << 20 | 15 << 4; } Tessellator.instance.setBrightness( b ); - if ( stat == 1 ) + if( stat == 1 ) Tessellator.instance.setColorOpaque_I( 0x00ff00 ); - if ( stat == 2 ) + if( stat == 2 ) Tessellator.instance.setColorOpaque_I( 0xffaa00 ); - if ( stat == 3 ) + if( stat == 3 ) Tessellator.instance.setColorOpaque_I( 0xff0000 ); this.selectFace( renderer, west, up, forward, 9, 10, 11, 12 ); this.renderFace( x, y, z, imb, ExtraBlockTextures.White.getIcon(), renderer, forward ); } b = world.getLightBrightnessForSkyBlocks( x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0 ); - if ( sp.isPowered() ) + if( sp.isPowered() ) { b = 15 << 20 | 15 << 4; } @@ -145,7 +148,7 @@ public class RenderMEChest extends BaseBlockRender IIcon ico = ch == null ? null : ch.getTopTexture_Light(); this.renderFace( x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up ); - if ( ico != null ) + if( ico != null ) { Tessellator.instance.setColorOpaque_I( sp.getColor().mediumVariant ); ico = ch == null ? null : ch.getTopTexture_Medium(); diff --git a/src/main/java/appeng/client/render/blocks/RenderNull.java b/src/main/java/appeng/client/render/blocks/RenderNull.java index 06091f564..0a9821a24 100644 --- a/src/main/java/appeng/client/render/blocks/RenderNull.java +++ b/src/main/java/appeng/client/render/blocks/RenderNull.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; @@ -26,23 +27,24 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import appeng.block.AEBaseBlock; import appeng.client.render.BaseBlockRender; + public class RenderNull extends BaseBlockRender { - public RenderNull() { + public RenderNull() + { super( false, 20 ); } @Override - public void renderInventory(AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { return true; } - } diff --git a/src/main/java/appeng/client/render/blocks/RenderQNB.java b/src/main/java/appeng/client/render/blocks/RenderQNB.java index d4b1aecde..753a0fcc8 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQNB.java +++ b/src/main/java/appeng/client/render/blocks/RenderQNB.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.Collection; import java.util.EnumSet; @@ -41,61 +42,12 @@ import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.qnb.TileQuantumBridge; + public class RenderQNB extends BaseBlockRender { - public void renderCableAt(double thickness, IBlockAccess world, int x, int y, int z, AEBaseBlock block, RenderBlocks renderer, IIcon texture, double pull, - Collection connections) - { - block.getRendererInstance().setTemporaryRenderIcon( texture ); - - if ( connections.contains( ForgeDirection.UNKNOWN ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.5D - thickness, 0.5D + thickness, 0.5D + thickness, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if ( connections.contains( ForgeDirection.WEST ) ) - { - renderer.setRenderBounds( 0.0D, 0.5D - thickness, 0.5D - thickness, 0.5D - thickness - pull, 0.5D + thickness, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if ( connections.contains( ForgeDirection.EAST ) ) - { - renderer.setRenderBounds( 0.5D + thickness + pull, 0.5D - thickness, 0.5D - thickness, 1.0D, 0.5D + thickness, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if ( connections.contains( ForgeDirection.NORTH ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.0D, 0.5D + thickness, 0.5D + thickness, 0.5D - thickness - pull ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if ( connections.contains( ForgeDirection.SOUTH ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.5D + thickness + pull, 0.5D + thickness, 0.5D + thickness, 1.0D ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if ( connections.contains( ForgeDirection.DOWN ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.0D, 0.5D - thickness, 0.5D + thickness, 0.5D - thickness - pull, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if ( connections.contains( ForgeDirection.UP ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D + thickness + pull, 0.5D - thickness, 0.5D + thickness, 1.0D, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( null ); - } - @Override - public void renderInventory(AEBaseBlock block, ItemStack item, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock block, ItemStack item, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { float minPx = 2.0f / 16.0f; float maxPx = 14.0f / 16.0f; @@ -105,10 +57,10 @@ public class RenderQNB extends BaseBlockRender } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { TileQuantumBridge tqb = block.getTileEntity( world, x, y, z ); - if ( tqb == null ) + if( tqb == null ) return false; renderer.renderAllFaces = true; @@ -117,11 +69,11 @@ public class RenderQNB extends BaseBlockRender final IBlocks blocks = definitions.blocks(); final IParts parts = definitions.parts(); - for ( Block linkBlock : blocks.quantumLink().maybeBlock().asSet() ) + for( Block linkBlock : blocks.quantumLink().maybeBlock().asSet() ) { - if ( tqb.getBlockType() == linkBlock ) + if( tqb.getBlockType() == linkBlock ) { - if ( tqb.isFormed() ) + if( tqb.isFormed() ) { EnumSet sides = tqb.getConnections(); @@ -139,18 +91,17 @@ public class RenderQNB extends BaseBlockRender } else { - if ( !tqb.isFormed() ) + if( !tqb.isFormed() ) { float renderMin = 2.0f / 16.0f; float renderMax = 14.0f / 16.0f; renderer.setRenderBounds( renderMin, renderMin, renderMin, renderMax, renderMax, renderMax ); renderer.renderStandardBlock( block, x, y, z ); } - else if ( tqb.isCorner() ) + else if( tqb.isCorner() ) { Item transCoveredCable = parts.cableCovered().item( AEColor.Transparent ); - this.renderCableAt( 0.188D, world, x, y, z, block, renderer, transCoveredCable.getIconIndex( parts.cableCovered().stack( AEColor.Transparent, 1 ) ), 0.05D, - tqb.getConnections() ); + this.renderCableAt( 0.188D, world, x, y, z, block, renderer, transCoveredCable.getIconIndex( parts.cableCovered().stack( AEColor.Transparent, 1 ) ), 0.05D, tqb.getConnections() ); float renderMin = 4.0f / 16.0f; float renderMax = 12.0f / 16.0f; @@ -158,7 +109,7 @@ public class RenderQNB extends BaseBlockRender renderer.setRenderBounds( renderMin, renderMin, renderMin, renderMax, renderMax, renderMax ); renderer.renderStandardBlock( block, x, y, z ); - if ( tqb.isPowered() ) + if( tqb.isPowered() ) { renderMin = 3.9f / 16.0f; @@ -168,9 +119,8 @@ public class RenderQNB extends BaseBlockRender int bn = 15; Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); Tessellator.instance.setBrightness( bn << 20 | bn << 4 ); - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) this.renderFace( x, y, z, block, ExtraBlockTextures.BlockQRingCornerLight.getIcon(), renderer, side ); - } } else @@ -186,7 +136,7 @@ public class RenderQNB extends BaseBlockRender renderer.setRenderBounds( renderMin, renderMin, 0, renderMax, renderMax, 1 ); renderer.renderStandardBlock( block, x, y, z ); - if ( tqb.isPowered() ) + if( tqb.isPowered() ) { renderMin = -0.01f / 16.0f; renderMax = 16.01f / 16.0f; @@ -195,7 +145,7 @@ public class RenderQNB extends BaseBlockRender int bn = 15; Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); Tessellator.instance.setBrightness( bn << 20 | bn << 4 ); - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) this.renderFace( x, y, z, block, ExtraBlockTextures.BlockQRingEdgeLight.getIcon(), renderer, side ); } } @@ -205,4 +155,53 @@ public class RenderQNB extends BaseBlockRender renderer.renderAllFaces = false; return true; } + + public void renderCableAt( double thickness, IBlockAccess world, int x, int y, int z, AEBaseBlock block, RenderBlocks renderer, IIcon texture, double pull, Collection connections ) + { + block.getRendererInstance().setTemporaryRenderIcon( texture ); + + if( connections.contains( ForgeDirection.UNKNOWN ) ) + { + renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.5D - thickness, 0.5D + thickness, 0.5D + thickness, 0.5D + thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + if( connections.contains( ForgeDirection.WEST ) ) + { + renderer.setRenderBounds( 0.0D, 0.5D - thickness, 0.5D - thickness, 0.5D - thickness - pull, 0.5D + thickness, 0.5D + thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + if( connections.contains( ForgeDirection.EAST ) ) + { + renderer.setRenderBounds( 0.5D + thickness + pull, 0.5D - thickness, 0.5D - thickness, 1.0D, 0.5D + thickness, 0.5D + thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + if( connections.contains( ForgeDirection.NORTH ) ) + { + renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.0D, 0.5D + thickness, 0.5D + thickness, 0.5D - thickness - pull ); + renderer.renderStandardBlock( block, x, y, z ); + } + + if( connections.contains( ForgeDirection.SOUTH ) ) + { + renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.5D + thickness + pull, 0.5D + thickness, 0.5D + thickness, 1.0D ); + renderer.renderStandardBlock( block, x, y, z ); + } + + if( connections.contains( ForgeDirection.DOWN ) ) + { + renderer.setRenderBounds( 0.5D - thickness, 0.0D, 0.5D - thickness, 0.5D + thickness, 0.5D - thickness - pull, 0.5D + thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + if( connections.contains( ForgeDirection.UP ) ) + { + renderer.setRenderBounds( 0.5D - thickness, 0.5D + thickness + pull, 0.5D - thickness, 0.5D + thickness, 1.0D, 0.5D + thickness ); + renderer.renderStandardBlock( block, x, y, z ); + } + + block.getRendererInstance().setTemporaryRenderIcon( null ); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderQuartzGlass.java b/src/main/java/appeng/client/render/blocks/RenderQuartzGlass.java index d5c37277f..bbc06bebe 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQuartzGlass.java +++ b/src/main/java/appeng/client/render/blocks/RenderQuartzGlass.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.Random; import net.minecraft.client.renderer.RenderBlocks; @@ -32,117 +33,27 @@ import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.client.texture.OffsetIcon; + public class RenderQuartzGlass extends BaseBlockRender { static byte[][][] offsets; - public RenderQuartzGlass() { + public RenderQuartzGlass() + { super( false, 0 ); - if ( offsets == null ) + if( offsets == null ) { Random r = new Random( 924 ); offsets = new byte[10][10][10]; - for (int x = 0; x < 10; x++) - for (int y = 0; y < 10; y++) + for( int x = 0; x < 10; x++ ) + for( int y = 0; y < 10; y++ ) r.nextBytes( offsets[x][y] ); } } - boolean isFlush(AEBaseBlock imb, IBlockAccess world, int x, int y, int z) - { - return this.isGlass( imb, world, x, y, z ); - } - - boolean isGlass(AEBaseBlock imb, IBlockAccess world, int x, int y, int z) - { - return this.isQuartzGlass( world, x, y, z ) || this.isVibrantQuartzGlass( world, x, y, z ); - } - - private boolean isQuartzGlass( IBlockAccess world, int x, int y, int z ) - { - return AEApi.instance().definitions().blocks().quartzGlass().isSameAs( world, x, y, z ); - } - - private boolean isVibrantQuartzGlass( IBlockAccess world, int x, int y, int z ) - { - return AEApi.instance().definitions().blocks().quartzVibrantGlass().isSameAs( world, x, y, z ); - } - - void renderEdge(AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer, ForgeDirection side, ForgeDirection direction) - { - if ( !this.isFlush( imb, world, x + side.offsetX, y + side.offsetY, z + side.offsetZ ) ) - { - if ( !this.isFlush( imb, world, x + direction.offsetX, y + direction.offsetY, z + direction.offsetZ ) ) - { - float minX = 0.5f + (side.offsetX + direction.offsetX) / 2.0f; - float minY = 0.5f + (side.offsetY + direction.offsetY) / 2.0f; - float minZ = 0.5f + (side.offsetZ + direction.offsetZ) / 2.0f; - float maxX = 0.5f + (side.offsetX + direction.offsetX) / 2.0f; - float maxY = 0.5f + (side.offsetY + direction.offsetY) / 2.0f; - float maxZ = 0.5f + (side.offsetZ + direction.offsetZ) / 2.0f; - - if ( 0 == side.offsetX && 0 == direction.offsetX ) - { - minX = 0.0f; - maxX = 1.0f; - } - if ( 0 == side.offsetY && 0 == direction.offsetY ) - { - minY = 0.0f; - maxY = 1.0f; - } - if ( 0 == side.offsetZ && 0 == direction.offsetZ ) - { - minZ = 0.0f; - maxZ = 1.0f; - } - - if ( maxX <= 0.001f ) - maxX += 0.9f / 16.0f; - if ( maxY <= 0.001f ) - maxY += 0.9f / 16.0f; - if ( maxZ <= 0.001f ) - maxZ += 0.9f / 16.0f; - - if ( minX >= 0.999f ) - minX -= 0.9f / 16.0f; - if ( minY >= 0.999f ) - minY -= 0.9f / 16.0f; - if ( minZ >= 0.999f ) - minZ -= 0.9f / 16.0f; - - renderer.setRenderBounds( minX, minY, minZ, maxX, maxY, maxZ ); - - switch (side) - { - case WEST: - renderer.renderFaceXNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case EAST: - renderer.renderFaceXPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case NORTH: - renderer.renderFaceZNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case SOUTH: - renderer.renderFaceZPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case DOWN: - renderer.renderFaceYNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case UP: - renderer.renderFaceYPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - default: - break; - } - } - } - } - @Override - public void renderInventory(AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { renderer.overrideBlockTexture = ExtraBlockTextures.GlassFrame.getIcon(); super.renderInventory( block, is, renderer, type, obj ); @@ -151,7 +62,7 @@ public class RenderQuartzGlass extends BaseBlockRender } @Override - public boolean renderInWorld(AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); @@ -162,20 +73,20 @@ public class RenderQuartzGlass extends BaseBlockRender int u = offsets[cx][cy][cz] % 4; int v = offsets[9 - cx][9 - cy][9 - cz] % 4; - switch (Math.abs( (offsets[cx][cy][cz] + (x + y + z)) % 4 )) + switch( Math.abs( ( offsets[cx][cy][cz] + ( x + y + z ) ) % 4 ) ) { - case 0: - renderer.overrideBlockTexture = new OffsetIcon( imb.getIcon( 0, 0 ), u / 2, v / 2 ); - break; - case 1: - renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassB.getIcon(), u / 2, v / 2 ); - break; - case 2: - renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassC.getIcon(), u, v ); - break; - case 3: - renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassD.getIcon(), u, v ); - break; + case 0: + renderer.overrideBlockTexture = new OffsetIcon( imb.getIcon( 0, 0 ), u / 2, v / 2 ); + break; + case 1: + renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassB.getIcon(), u / 2, v / 2 ); + break; + case 2: + renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassC.getIcon(), u, v ); + break; + case 3: + renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassD.getIcon(), u, v ); + break; } boolean result = renderer.renderStandardBlock( imb, x, y, z ); @@ -214,4 +125,95 @@ public class RenderQuartzGlass extends BaseBlockRender return result; } + void renderEdge( AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer, ForgeDirection side, ForgeDirection direction ) + { + if( !this.isFlush( imb, world, x + side.offsetX, y + side.offsetY, z + side.offsetZ ) ) + { + if( !this.isFlush( imb, world, x + direction.offsetX, y + direction.offsetY, z + direction.offsetZ ) ) + { + float minX = 0.5f + ( side.offsetX + direction.offsetX ) / 2.0f; + float minY = 0.5f + ( side.offsetY + direction.offsetY ) / 2.0f; + float minZ = 0.5f + ( side.offsetZ + direction.offsetZ ) / 2.0f; + float maxX = 0.5f + ( side.offsetX + direction.offsetX ) / 2.0f; + float maxY = 0.5f + ( side.offsetY + direction.offsetY ) / 2.0f; + float maxZ = 0.5f + ( side.offsetZ + direction.offsetZ ) / 2.0f; + + if( 0 == side.offsetX && 0 == direction.offsetX ) + { + minX = 0.0f; + maxX = 1.0f; + } + if( 0 == side.offsetY && 0 == direction.offsetY ) + { + minY = 0.0f; + maxY = 1.0f; + } + if( 0 == side.offsetZ && 0 == direction.offsetZ ) + { + minZ = 0.0f; + maxZ = 1.0f; + } + + if( maxX <= 0.001f ) + maxX += 0.9f / 16.0f; + if( maxY <= 0.001f ) + maxY += 0.9f / 16.0f; + if( maxZ <= 0.001f ) + maxZ += 0.9f / 16.0f; + + if( minX >= 0.999f ) + minX -= 0.9f / 16.0f; + if( minY >= 0.999f ) + minY -= 0.9f / 16.0f; + if( minZ >= 0.999f ) + minZ -= 0.9f / 16.0f; + + renderer.setRenderBounds( minX, minY, minZ, maxX, maxY, maxZ ); + + switch( side ) + { + case WEST: + renderer.renderFaceXNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); + break; + case EAST: + renderer.renderFaceXPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); + break; + case NORTH: + renderer.renderFaceZNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); + break; + case SOUTH: + renderer.renderFaceZPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); + break; + case DOWN: + renderer.renderFaceYNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); + break; + case UP: + renderer.renderFaceYPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); + break; + default: + break; + } + } + } + } + + boolean isFlush( AEBaseBlock imb, IBlockAccess world, int x, int y, int z ) + { + return this.isGlass( imb, world, x, y, z ); + } + + boolean isGlass( AEBaseBlock imb, IBlockAccess world, int x, int y, int z ) + { + return this.isQuartzGlass( world, x, y, z ) || this.isVibrantQuartzGlass( world, x, y, z ); + } + + private boolean isQuartzGlass( IBlockAccess world, int x, int y, int z ) + { + return AEApi.instance().definitions().blocks().quartzGlass().isSameAs( world, x, y, z ); + } + + private boolean isVibrantQuartzGlass( IBlockAccess world, int x, int y, int z ) + { + return AEApi.instance().definitions().blocks().quartzVibrantGlass().isSameAs( world, x, y, z ); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java b/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java index 79405ecc0..63b404e64 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java +++ b/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; @@ -28,15 +29,17 @@ import appeng.block.solids.OreQuartz; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; + public class RenderQuartzOre extends BaseBlockRender { - public RenderQuartzOre() { + public RenderQuartzOre() + { super( false, 20 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { super.renderInventory( blk, is, renderer, type, obj ); blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.OreQuartzStone.getIcon() ); @@ -45,7 +48,7 @@ public class RenderQuartzOre extends BaseBlockRender } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { OreQuartz blk = (OreQuartz) block; blk.setEnhanceBrightness( true ); diff --git a/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java b/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java index 0bbbe9e93..a5c60da02 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java +++ b/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; @@ -34,15 +35,17 @@ import appeng.block.AEBaseBlock; import appeng.block.misc.BlockQuartzTorch; import appeng.client.render.BaseBlockRender; + public class RenderQuartzTorch extends BaseBlockRender { - public RenderQuartzTorch() { + public RenderQuartzTorch() + { super( false, 20 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { Tessellator tess = Tessellator.instance; @@ -90,15 +93,14 @@ public class RenderQuartzTorch extends BaseBlockRender renderer.renderAllFaces = false; blk.getRendererInstance().setTemporaryRenderIcon( null ); - } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { BlockQuartzTorch blk = (BlockQuartzTorch) block; - IOrientable te = ((IOrientableBlock) block).getOrientable( world, x, y, z ); + IOrientable te = ( (IOrientableBlock) block ).getOrientable( world, x, y, z ); float Point2 = 6.0f / 16.0f; float Point3 = 7.0f / 16.0f; @@ -117,19 +119,19 @@ public class RenderQuartzTorch extends BaseBlockRender float zOff = 0.0f; renderer.renderAllFaces = true; - if ( te != null ) + if( te != null ) { ForgeDirection forward = te.getUp(); - xOff = forward.offsetX * -(4.0f / 16.0f); - yOff = forward.offsetY * -(4.0f / 16.0f); - zOff = forward.offsetZ * -(4.0f / 16.0f); + xOff = forward.offsetX * -( 4.0f / 16.0f ); + yOff = forward.offsetY * -( 4.0f / 16.0f ); + zOff = forward.offsetZ * -( 4.0f / 16.0f ); } renderer.setRenderBounds( Point3 + xOff, renderBottom + yOff, Point3 + zOff, Point12 + xOff, renderTop + yOff, Point12 + zOff ); super.renderInWorld( block, world, x, y, z, renderer ); - int r = (x + y + z) % 2; - if ( r == 0 ) + int r = ( x + y + z ) % 2; + if( r == 0 ) { renderer.setRenderBounds( Point3 + xOff, renderTop + yOff, Point3 + zOff, Point3 + singlePixel + xOff, renderTop + singlePixel + yOff, Point3 + singlePixel + zOff ); super.renderInWorld( block, world, x, y, z, renderer ); @@ -160,48 +162,48 @@ public class RenderQuartzTorch extends BaseBlockRender renderer.setRenderBounds( Point12 + xOff, bottom + yOff, Point3 + zOff, Point13 + xOff, top + yOff, Point12 + zOff ); renderer.renderStandardBlock( blk, x, y, z ); - if ( te != null ) + if( te != null ) { ForgeDirection forward = te.getUp(); - switch (forward) + switch( forward ) { - case EAST: - renderer.setRenderBounds( 0, bottom + yOff, bottom + zOff, Point2 + xOff, top + yOff, top + zOff ); - renderer.renderStandardBlock( blk, x, y, z ); - break; - case WEST: - renderer.setRenderBounds( Point13 + xOff, bottom + yOff, bottom + zOff, 1.0, top + yOff, top + zOff ); - renderer.renderStandardBlock( blk, x, y, z ); - break; - case NORTH: - renderer.setRenderBounds( bottom + xOff, bottom + yOff, Point13 + zOff, top + xOff, top + yOff, 1.0 ); - renderer.renderStandardBlock( blk, x, y, z ); - break; - case SOUTH: - renderer.setRenderBounds( bottom + xOff, bottom + yOff, 0, top + xOff, top + yOff, Point2 + zOff ); - renderer.renderStandardBlock( blk, x, y, z ); - break; - case UP: - renderer.setRenderBounds( Point2, 0, Point2, Point3, bottom + yOff, Point3 ); - renderer.renderStandardBlock( blk, x, y, z ); - renderer.setRenderBounds( Point2, 0, Point12, Point3, bottom + yOff, Point13 ); - renderer.renderStandardBlock( blk, x, y, z ); - renderer.setRenderBounds( Point12, 0, Point2, Point13, bottom + yOff, Point3 ); - renderer.renderStandardBlock( blk, x, y, z ); - renderer.setRenderBounds( Point12, 0, Point12, Point13, bottom + yOff, Point13 ); - renderer.renderStandardBlock( blk, x, y, z ); - break; - case DOWN: - renderer.setRenderBounds( Point2, top + yOff, Point2, Point3, 1.0, Point3 ); - renderer.renderStandardBlock( blk, x, y, z ); - renderer.setRenderBounds( Point2, top + yOff, Point12, Point3, 1.0, Point13 ); - renderer.renderStandardBlock( blk, x, y, z ); - renderer.setRenderBounds( Point12, top + yOff, Point2, Point13, 1.0, Point3 ); - renderer.renderStandardBlock( blk, x, y, z ); - renderer.setRenderBounds( Point12, top + yOff, Point12, Point13, 1.0, Point13 ); - renderer.renderStandardBlock( blk, x, y, z ); - break; - default: + case EAST: + renderer.setRenderBounds( 0, bottom + yOff, bottom + zOff, Point2 + xOff, top + yOff, top + zOff ); + renderer.renderStandardBlock( blk, x, y, z ); + break; + case WEST: + renderer.setRenderBounds( Point13 + xOff, bottom + yOff, bottom + zOff, 1.0, top + yOff, top + zOff ); + renderer.renderStandardBlock( blk, x, y, z ); + break; + case NORTH: + renderer.setRenderBounds( bottom + xOff, bottom + yOff, Point13 + zOff, top + xOff, top + yOff, 1.0 ); + renderer.renderStandardBlock( blk, x, y, z ); + break; + case SOUTH: + renderer.setRenderBounds( bottom + xOff, bottom + yOff, 0, top + xOff, top + yOff, Point2 + zOff ); + renderer.renderStandardBlock( blk, x, y, z ); + break; + case UP: + renderer.setRenderBounds( Point2, 0, Point2, Point3, bottom + yOff, Point3 ); + renderer.renderStandardBlock( blk, x, y, z ); + renderer.setRenderBounds( Point2, 0, Point12, Point3, bottom + yOff, Point13 ); + renderer.renderStandardBlock( blk, x, y, z ); + renderer.setRenderBounds( Point12, 0, Point2, Point13, bottom + yOff, Point3 ); + renderer.renderStandardBlock( blk, x, y, z ); + renderer.setRenderBounds( Point12, 0, Point12, Point13, bottom + yOff, Point13 ); + renderer.renderStandardBlock( blk, x, y, z ); + break; + case DOWN: + renderer.setRenderBounds( Point2, top + yOff, Point2, Point3, 1.0, Point3 ); + renderer.renderStandardBlock( blk, x, y, z ); + renderer.setRenderBounds( Point2, top + yOff, Point12, Point3, 1.0, Point13 ); + renderer.renderStandardBlock( blk, x, y, z ); + renderer.setRenderBounds( Point12, top + yOff, Point2, Point13, 1.0, Point3 ); + renderer.renderStandardBlock( blk, x, y, z ); + renderer.setRenderBounds( Point12, top + yOff, Point12, Point13, 1.0, Point13 ); + renderer.renderStandardBlock( blk, x, y, z ); + break; + default: } } diff --git a/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java b/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java index 15ba91b3d..92328ee33 100644 --- a/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java +++ b/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; @@ -26,22 +27,24 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import appeng.block.AEBaseBlock; import appeng.client.render.BaseBlockRender; + public class RenderTinyTNT extends BaseBlockRender { - public RenderTinyTNT() { + public RenderTinyTNT() + { super( false, 0 ); } @Override - public void renderInventory(AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { renderer.setRenderBounds( 0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f ); super.renderInventory( block, is, renderer, type, obj ); } @Override - public boolean renderInWorld(AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { renderer.renderAllFaces = true; renderer.setRenderBounds( 0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f ); @@ -49,5 +52,4 @@ public class RenderTinyTNT extends BaseBlockRender renderer.renderAllFaces = false; return out; } - } diff --git a/src/main/java/appeng/client/render/blocks/RendererCableBus.java b/src/main/java/appeng/client/render/blocks/RendererCableBus.java index e04f02917..6b67793bc 100644 --- a/src/main/java/appeng/client/render/blocks/RendererCableBus.java +++ b/src/main/java/appeng/client/render/blocks/RendererCableBus.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -31,30 +32,32 @@ import appeng.client.render.BusRenderer; import appeng.tile.AEBaseTile; import appeng.tile.networking.TileCableBus; + public class RendererCableBus extends BaseBlockRender { - public RendererCableBus() { + public RendererCableBus() + { super( true, 30 ); } @Override - public void renderInventory(AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock blk, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { // nothing. } @Override - public boolean renderInWorld(AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock block, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { AEBaseTile t = block.getTileEntity( world, x, y, z ); - if ( t instanceof TileCableBus ) + if( t instanceof TileCableBus ) { BusRenderer.INSTANCE.renderer.renderAllFaces = true; BusRenderer.INSTANCE.renderer.blockAccess = renderer.blockAccess; BusRenderer.INSTANCE.renderer.overrideBlockTexture = renderer.overrideBlockTexture; - ((TileCableBus) t).cb.renderStatic( x, y, z ); + ( (TileCableBus) t ).cb.renderStatic( x, y, z ); BusRenderer.INSTANCE.renderer.renderAllFaces = false; } @@ -62,13 +65,12 @@ public class RendererCableBus extends BaseBlockRender } @Override - public void renderTile(AEBaseBlock block, AEBaseTile t, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer) + public void renderTile( AEBaseBlock block, AEBaseTile t, Tessellator tess, double x, double y, double z, float f, RenderBlocks renderer ) { - if ( t instanceof TileCableBus ) + if( t instanceof TileCableBus ) { BusRenderer.INSTANCE.renderer.overrideBlockTexture = null; - ((TileCableBus) t).cb.renderDynamic( x, y, z ); + ( (TileCableBus) t ).cb.renderDynamic( x, y, z ); } } - } diff --git a/src/main/java/appeng/client/render/blocks/RendererSecurity.java b/src/main/java/appeng/client/render/blocks/RendererSecurity.java index 3ad7594bc..9392a962d 100644 --- a/src/main/java/appeng/client/render/blocks/RendererSecurity.java +++ b/src/main/java/appeng/client/render/blocks/RendererSecurity.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; + import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; @@ -34,29 +35,30 @@ import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.misc.TileSecurity; + public class RendererSecurity extends BaseBlockRender { - public RendererSecurity() { + public RendererSecurity() + { super( false, 0 ); } @Override - public void renderInventory(AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj) + public void renderInventory( AEBaseBlock block, ItemStack is, RenderBlocks renderer, ItemRenderType type, Object[] obj ) { renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); - this.renderInvBlock( EnumSet.of( ForgeDirection.UP ), block, is, Tessellator.instance, this.adjustBrightness( AEColor.Transparent.whiteVariant, 0.7 ), - renderer ); + this.renderInvBlock( EnumSet.of( ForgeDirection.UP ), block, is, Tessellator.instance, this.adjustBrightness( AEColor.Transparent.whiteVariant, 0.7 ), renderer ); renderer.overrideBlockTexture = null; super.renderInventory( block, is, renderer, type, obj ); } @Override - public boolean renderInWorld(AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) + public boolean renderInWorld( AEBaseBlock imb, IBlockAccess world, int x, int y, int z, RenderBlocks renderer ) { TileSecurity sp = imb.getTileEntity( world, x, y, z ); renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); @@ -68,7 +70,7 @@ public class RendererSecurity extends BaseBlockRender boolean result = renderer.renderStandardBlock( imb, x, y, z ); int b = world.getLightBrightnessForSkyBlocks( x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0 ); - if ( sp.isActive() ) + if( sp.isActive() ) { b = 15 << 20 | 15 << 4; } @@ -80,7 +82,7 @@ public class RendererSecurity extends BaseBlockRender Tessellator.instance.setColorOpaque_I( sp.getColor().whiteVariant ); IIcon ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Light.getIcon() : ExtraBlockTextures.MEChest.getIcon(); this.renderFace( x, y, z, imb, ico, renderer, up ); - if ( sp.isActive() ) + if( sp.isActive() ) { Tessellator.instance.setColorOpaque_I( sp.getColor().mediumVariant ); ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Medium.getIcon() : ExtraBlockTextures.MEChest.getIcon(); diff --git a/src/main/java/appeng/client/render/effects/AssemblerFX.java b/src/main/java/appeng/client/render/effects/AssemblerFX.java index 324c37a6f..7cee38037 100644 --- a/src/main/java/appeng/client/render/effects/AssemblerFX.java +++ b/src/main/java/appeng/client/render/effects/AssemblerFX.java @@ -34,8 +34,8 @@ public class AssemblerFX extends EntityFX final IAEItemStack item; final EntityFloatingItem fi; - float time = 0; final float speed; + float time = 0; public AssemblerFX( World w, double x, double y, double z, double r, double g, double b, float speed, IAEItemStack is ) { @@ -47,7 +47,7 @@ public class AssemblerFX extends EntityFX this.speed = speed; this.fi = new EntityFloatingItem( this, w, x, y, z, is.getItemStack() ); w.spawnEntityInWorld( this.fi ); - this.particleMaxAge = ( int ) Math.ceil( Math.max( 1, 100.0f / speed ) ) + 2; + this.particleMaxAge = (int) Math.ceil( Math.max( 1, 100.0f / speed ) ) + 2; this.noClip = true; } @@ -63,11 +63,11 @@ public class AssemblerFX extends EntityFX { super.onUpdate(); - if ( this.isDead ) + if( this.isDead ) this.fi.setDead(); else { - float lifeSpan = ( float ) this.particleAge / ( float ) this.particleMaxAge; + float lifeSpan = (float) this.particleAge / (float) this.particleMaxAge; this.fi.setProgress( lifeSpan ); } } @@ -76,13 +76,12 @@ public class AssemblerFX extends EntityFX public void renderParticle( Tessellator tess, float l, float rX, float rY, float rZ, float rYZ, float rXY ) { this.time += l; - if ( this.time > 4.0 ) + if( this.time > 4.0 ) { this.time -= 4.0; // if ( CommonHelper.proxy.shouldAddParticles( r ) ) - for ( int x = 0; x < ( int ) Math.ceil( this.speed / 5 ); x++ ) + for( int x = 0; x < (int) Math.ceil( this.speed / 5 ); x++ ) CommonHelper.proxy.spawnEffect( EffectType.Crafting, this.worldObj, this.posX, this.posY, this.posZ, null ); } } - } diff --git a/src/main/java/appeng/client/render/effects/ChargedOreFX.java b/src/main/java/appeng/client/render/effects/ChargedOreFX.java index 5f06de701..5ba8023d1 100644 --- a/src/main/java/appeng/client/render/effects/ChargedOreFX.java +++ b/src/main/java/appeng/client/render/effects/ChargedOreFX.java @@ -29,7 +29,6 @@ public class ChargedOreFX extends EntityReddustFX public ChargedOreFX( World w, double x, double y, double z, float r, float g, float b ) { super( w, x, y, z, 0.21f, 0.61f, 1.0f ); - } @Override @@ -38,9 +37,8 @@ public class ChargedOreFX extends EntityReddustFX int j1 = super.getBrightnessForRender( par1 ); j1 = Math.max( j1 >> 20, j1 >> 4 ); j1 += 3; - if ( j1 > 15 ) + if( j1 > 15 ) j1 = 15; return j1 << 20 | j1 << 4; } - } diff --git a/src/main/java/appeng/client/render/effects/CraftingFx.java b/src/main/java/appeng/client/render/effects/CraftingFx.java index 797e00b82..3b60cb2bf 100644 --- a/src/main/java/appeng/client/render/effects/CraftingFx.java +++ b/src/main/java/appeng/client/render/effects/CraftingFx.java @@ -43,12 +43,6 @@ public class CraftingFx extends EntityBreakingFX private final int startBlkY; private final int startBlkZ; - @Override - public int getFXLayer() - { - return 1; - } - public CraftingFx( World par1World, double par2, double par4, double par6, Item par8Item ) { super( par1World, par2, par4, par6, par8Item ); @@ -68,6 +62,47 @@ public class CraftingFx extends EntityBreakingFX this.noClip = true; } + @Override + public int getFXLayer() + { + return 1; + } + + @Override + public void renderParticle( Tessellator par1Tessellator, float partialTick, float x, float y, float z, float rx, float rz ) + { + if( partialTick < 0 || partialTick > 1 ) + return; + + float f6 = this.particleTextureIndex.getMinU(); + float f7 = this.particleTextureIndex.getMaxU(); + float f8 = this.particleTextureIndex.getMinV(); + float f9 = this.particleTextureIndex.getMaxV(); + float scale = 0.1F * this.particleScale; + + float offX = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * partialTick ); + float offY = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * partialTick ); + float offZ = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * partialTick ); + float f14 = 1.0F; + + int blkX = MathHelper.floor_double( offX ); + int blkY = MathHelper.floor_double( offY ); + int blkZ = MathHelper.floor_double( offZ ); + if( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) + { + offX -= interpPosX; + offY -= interpPosY; + offZ -= interpPosZ; + + // AELog.info( "" + partialTick ); + par1Tessellator.setColorRGBA_F( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ); + par1Tessellator.addVertexWithUV( offX - x * scale - rx * scale, offY - y * scale, offZ - z * scale - rz * scale, f7, f9 ); + par1Tessellator.addVertexWithUV( offX - x * scale + rx * scale, offY + y * scale, offZ - z * scale + rz * scale, f7, f8 ); + par1Tessellator.addVertexWithUV( offX + x * scale + rx * scale, offY + y * scale, offZ + z * scale + rz * scale, f6, f8 ); + par1Tessellator.addVertexWithUV( offX + x * scale - rx * scale, offY - y * scale, offZ + z * scale - rz * scale, f6, f9 ); + } + } + public void fromItem( ForgeDirection d ) { this.posX += 0.2 * d.offsetX; @@ -83,44 +118,4 @@ public class CraftingFx extends EntityBreakingFX this.particleScale *= 0.51f; this.particleAlpha *= 0.51f; } - - @Override - public void renderParticle( Tessellator par1Tessellator, float partialTick, float x, float y, float z, float rx, float rz ) - { - if ( partialTick < 0 || partialTick > 1 ) - return; - - float f6 = this.particleTextureIndex.getMinU(); - float f7 = this.particleTextureIndex.getMaxU(); - float f8 = this.particleTextureIndex.getMinV(); - float f9 = this.particleTextureIndex.getMaxV(); - float scale = 0.1F * this.particleScale; - - float offX = ( float ) ( this.prevPosX + ( this.posX - this.prevPosX ) * partialTick ); - float offY = ( float ) ( this.prevPosY + ( this.posY - this.prevPosY ) * partialTick ); - float offZ = ( float ) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * partialTick ); - float f14 = 1.0F; - - int blkX = MathHelper.floor_double( offX ); - int blkY = MathHelper.floor_double( offY ); - int blkZ = MathHelper.floor_double( offZ ); - if ( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) - { - offX -= interpPosX; - offY -= interpPosY; - offZ -= interpPosZ; - - // AELog.info( "" + partialTick ); - par1Tessellator.setColorRGBA_F( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ); - par1Tessellator.addVertexWithUV( offX - x * scale - rx * scale, offY - y * scale, offZ - z * scale - rz * scale, - f7, f9 ); - par1Tessellator.addVertexWithUV( offX - x * scale + rx * scale, offY + y * scale, offZ - z * scale + rz * scale, - f7, f8 ); - par1Tessellator.addVertexWithUV( offX + x * scale + rx * scale, offY + y * scale, offZ + z * scale + rz * scale, - f6, f8 ); - par1Tessellator.addVertexWithUV( offX + x * scale - rx * scale, offY - y * scale, offZ + z * scale - rz * scale, - f6, f9 ); - } - } - } diff --git a/src/main/java/appeng/client/render/effects/EnergyFx.java b/src/main/java/appeng/client/render/effects/EnergyFx.java index 5cd697ae5..94ed79d71 100644 --- a/src/main/java/appeng/client/render/effects/EnergyFx.java +++ b/src/main/java/appeng/client/render/effects/EnergyFx.java @@ -43,12 +43,6 @@ public class EnergyFx extends EntityBreakingFX private final int startBlkY; private final int startBlkZ; - @Override - public int getFXLayer() - { - return 1; - } - public EnergyFx( World par1World, double par2, double par4, double par6, Item par8Item ) { super( par1World, par2, par4, par6, par8Item ); @@ -67,6 +61,40 @@ public class EnergyFx extends EntityBreakingFX this.noClip = true; } + @Override + public int getFXLayer() + { + return 1; + } + + @Override + public void renderParticle( Tessellator par1Tessellator, float par2, float par3, float par4, float par5, float par6, float par7 ) + { + float f6 = this.particleTextureIndex.getMinU(); + float f7 = this.particleTextureIndex.getMaxU(); + float f8 = this.particleTextureIndex.getMinV(); + float f9 = this.particleTextureIndex.getMaxV(); + float f10 = 0.1F * this.particleScale; + + float f11 = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); + float f12 = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); + float f13 = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); + float f14 = 1.0F; + + int blkX = MathHelper.floor_double( this.posX ); + int blkY = MathHelper.floor_double( this.posY ); + int blkZ = MathHelper.floor_double( this.posZ ); + + if( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) + { + par1Tessellator.setColorRGBA_F( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ); + par1Tessellator.addVertexWithUV( f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f7, f9 ); + par1Tessellator.addVertexWithUV( f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f7, f8 ); + par1Tessellator.addVertexWithUV( f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f6, f8 ); + par1Tessellator.addVertexWithUV( f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f6, f9 ); + } + } + public void fromItem( ForgeDirection d ) { this.posX += 0.2 * d.offsetX; @@ -82,37 +110,4 @@ public class EnergyFx extends EntityBreakingFX this.particleScale *= 0.89f; this.particleAlpha *= 0.89f; } - - @Override - public void renderParticle( Tessellator par1Tessellator, float par2, float par3, float par4, float par5, float par6, float par7 ) - { - float f6 = this.particleTextureIndex.getMinU(); - float f7 = this.particleTextureIndex.getMaxU(); - float f8 = this.particleTextureIndex.getMinV(); - float f9 = this.particleTextureIndex.getMaxV(); - float f10 = 0.1F * this.particleScale; - - float f11 = ( float ) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); - float f12 = ( float ) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); - float f13 = ( float ) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); - float f14 = 1.0F; - - int blkX = MathHelper.floor_double( this.posX ); - int blkY = MathHelper.floor_double( this.posY ); - int blkZ = MathHelper.floor_double( this.posZ ); - - if ( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) - { - par1Tessellator.setColorRGBA_F( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ); - par1Tessellator.addVertexWithUV( f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, - f7, f9 ); - par1Tessellator.addVertexWithUV( f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, - f7, f8 ); - par1Tessellator.addVertexWithUV( f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, - f6, f8 ); - par1Tessellator.addVertexWithUV( f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, - f6, f9 ); - } - } - } diff --git a/src/main/java/appeng/client/render/effects/LightningArcFX.java b/src/main/java/appeng/client/render/effects/LightningArcFX.java index 9680915b4..2caa85491 100644 --- a/src/main/java/appeng/client/render/effects/LightningArcFX.java +++ b/src/main/java/appeng/client/render/effects/LightningArcFX.java @@ -53,13 +53,11 @@ public class LightningArcFX extends LightningFX double lastDirectionZ = this.rz * i; double len = Math.sqrt( lastDirectionX * lastDirectionX + lastDirectionY * lastDirectionY + lastDirectionZ * lastDirectionZ ); - for ( int s = 0; s < this.steps; s++ ) + for( int s = 0; s < this.steps; s++ ) { this.Steps[s][0] = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; this.Steps[s][1] = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; this.Steps[s][2] = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; } - } - } diff --git a/src/main/java/appeng/client/render/effects/LightningFX.java b/src/main/java/appeng/client/render/effects/LightningFX.java index 651dcb1dd..5db2f22f6 100644 --- a/src/main/java/appeng/client/render/effects/LightningFX.java +++ b/src/main/java/appeng/client/render/effects/LightningFX.java @@ -32,9 +32,19 @@ import net.minecraft.world.World; public class LightningFX extends EntityFX { - final int steps = this.getSteps(); private static final Random RANDOM_GENERATOR = new Random(); + final int steps = this.getSteps(); final double[][] Steps; + final double[] I = new double[3]; + final double[] K = new double[3]; + float currentPoint = 0; + boolean hasData = false; + + public LightningFX( World w, double x, double y, double z, double r, double g, double b ) + { + this( w, x, y, z, r, g, b, 6 ); + this.regen(); + } protected LightningFX( World w, double x, double y, double z, double r, double g, double b, int maxAge ) { @@ -47,19 +57,24 @@ public class LightningFX extends EntityFX this.noClip = true; } + protected void regen() + { + double lastDirectionX = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; + double lastDirectionY = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; + double lastDirectionZ = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; + for( int s = 0; s < this.steps; s++ ) + { + this.Steps[s][0] = lastDirectionX = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; + this.Steps[s][1] = lastDirectionY = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; + this.Steps[s][2] = lastDirectionZ = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; + } + } + private int getSteps() { return 5; } - public LightningFX( World w, double x, double y, double z, double r, double g, double b ) - { - this( w, x, y, z, r, g, b, 6 ); - this.regen(); - } - - float currentPoint = 0; - @Override public int getBrightnessForRender( float par1 ) { @@ -67,25 +82,12 @@ public class LightningFX extends EntityFX return j1 << 20 | j1 << 4; } - protected void regen() - { - double lastDirectionX = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - double lastDirectionY = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - double lastDirectionZ = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - for ( int s = 0; s < this.steps; s++ ) - { - this.Steps[s][0] = lastDirectionX = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - this.Steps[s][1] = lastDirectionY = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - this.Steps[s][2] = lastDirectionZ = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - } - } - @Override public void renderParticle( Tessellator tess, float l, float rX, float rY, float rZ, float rYZ, float rXY ) { float j = 1.0f; tess.setColorRGBA_F( this.particleRed * j * 0.9f, this.particleGreen * j * 0.95f, this.particleBlue * j, this.particleAlpha ); - if ( this.particleAge == 3 ) + if( this.particleAge == 3 ) { this.regen(); } @@ -108,12 +110,12 @@ public class LightningFX extends EntityFX EntityPlayer p = Minecraft.getMinecraft().thePlayer; double offX = -rZ; - double offY = MathHelper.cos( ( float ) ( Math.PI / 2.0f + p.rotationPitch * 0.017453292F ) ); + double offY = MathHelper.cos( (float) ( Math.PI / 2.0f + p.rotationPitch * 0.017453292F ) ); double offZ = rX; - for ( int layer = 0; layer < 2; layer++ ) + for( int layer = 0; layer < 2; layer++ ) { - if ( layer == 0 ) + if( layer == 0 ) { scale = 0.04; offX *= 0.001; @@ -130,7 +132,7 @@ public class LightningFX extends EntityFX tess.setColorRGBA_F( this.particleRed * j * 0.9f, this.particleGreen * j * 0.65f, this.particleBlue * j * 0.85f, this.particleAlpha ); } - for ( int cycle = 0; cycle < 3; cycle++ ) + for( int cycle = 0; cycle < 3; cycle++ ) { this.clear(); @@ -138,7 +140,7 @@ public class LightningFX extends EntityFX double y = ( this.prevPosY + ( this.posY - this.prevPosY ) * l - interpPosY ) - offY; double z = ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * l - interpPosZ ) - offZ; - for ( int s = 0; s < this.steps; s++ ) + for( int s = 0; s < this.steps; s++ ) { double xN = x + this.Steps[s][0]; double yN = y + this.Steps[s][1]; @@ -148,26 +150,26 @@ public class LightningFX extends EntityFX double yD = yN - y; double zD = zN - z; - if ( cycle == 0 ) + if( cycle == 0 ) { ox = ( yD * 0 ) - ( 1 * zD ); oy = ( zD * 0 ) - ( 0 * xD ); oz = ( xD * 1 ) - ( 0 * yD ); } - if ( cycle == 1 ) + if( cycle == 1 ) { ox = ( yD * 1 ) - ( 0 * zD ); oy = ( zD * 0 ) - ( 1 * xD ); oz = ( xD * 0 ) - ( 0 * yD ); } - if ( cycle == 2 ) + if( cycle == 2 ) { ox = ( yD * 0 ) - ( 0 * zD ); oy = ( zD * 1 ) - ( 0 * xD ); oz = ( xD * 0 ) - ( 1 * yD ); } - double ss = Math.sqrt( ox * ox + oy * oy + oz * oz ) / ( ( ( ( double ) this.steps - ( double ) s ) / this.steps ) * scale ); + double ss = Math.sqrt( ox * ox + oy * oy + oz * oz ) / ( ( ( (double) this.steps - (double) s ) / this.steps ) * scale ); ox /= ss; oy /= ss; oz /= ss; @@ -194,13 +196,14 @@ public class LightningFX extends EntityFX */ } - boolean hasData = false; - final double[] I = new double[3]; - final double[] K = new double[3]; + private void clear() + { + this.hasData = false; + } private void draw( Tessellator tess, double[] a, double[] b, double f6, double f8 ) { - if ( this.hasData ) + if( this.hasData ) { tess.addVertexWithUV( a[0], a[1], a[2], f6, f8 ); tess.addVertexWithUV( this.I[0], this.I[1], this.I[2], f6, f8 ); @@ -208,15 +211,10 @@ public class LightningFX extends EntityFX tess.addVertexWithUV( b[0], b[1], b[2], f6, f8 ); } this.hasData = true; - for ( int x = 0; x < 3; x++ ) + for( int x = 0; x < 3; x++ ) { this.I[x] = a[x]; this.K[x] = b[x]; } } - - private void clear() - { - this.hasData = false; - } } diff --git a/src/main/java/appeng/client/render/effects/MatterCannonFX.java b/src/main/java/appeng/client/render/effects/MatterCannonFX.java index a5502bb45..7efaae48c 100644 --- a/src/main/java/appeng/client/render/effects/MatterCannonFX.java +++ b/src/main/java/appeng/client/render/effects/MatterCannonFX.java @@ -78,20 +78,15 @@ public class MatterCannonFX extends EntityBreakingFX float f9 = this.particleTextureIndex.getMaxV(); float f10 = 0.05F * this.particleScale; - float f11 = ( float ) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); - float f12 = ( float ) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); - float f13 = ( float ) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); + float f11 = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); + float f12 = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); + float f13 = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); float f14 = 1.0F; par1Tessellator.setColorRGBA_F( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ); - par1Tessellator.addVertexWithUV( f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, - f7, f9 ); - par1Tessellator.addVertexWithUV( f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, - f7, f8 ); - par1Tessellator.addVertexWithUV( f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, - f6, f8 ); - par1Tessellator.addVertexWithUV( f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, - f6, f9 ); + par1Tessellator.addVertexWithUV( f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f7, f9 ); + par1Tessellator.addVertexWithUV( f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f7, f8 ); + par1Tessellator.addVertexWithUV( f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f6, f8 ); + par1Tessellator.addVertexWithUV( f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f6, f9 ); } - } diff --git a/src/main/java/appeng/client/render/effects/VibrantFX.java b/src/main/java/appeng/client/render/effects/VibrantFX.java index 4f4dda8eb..5a94a3c57 100644 --- a/src/main/java/appeng/client/render/effects/VibrantFX.java +++ b/src/main/java/appeng/client/render/effects/VibrantFX.java @@ -46,7 +46,7 @@ public class VibrantFX extends EntityFX this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; - this.particleMaxAge = ( int ) ( 20.0D / ( Math.random() * 0.8D + 0.1D ) ); + this.particleMaxAge = (int) ( 20.0D / ( Math.random() * 0.8D + 0.1D ) ); this.noClip = true; } @@ -68,7 +68,7 @@ public class VibrantFX extends EntityFX // this.moveEntity(this.motionX, this.motionY, this.motionZ); this.particleScale *= 0.95; - if ( this.particleMaxAge <= 0 || this.particleScale < 0.1 ) + if( this.particleMaxAge <= 0 || this.particleScale < 0.1 ) { this.setDead(); } diff --git a/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java b/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java index b03bb20d2..aa33343e5 100644 --- a/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java +++ b/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java @@ -18,6 +18,7 @@ package appeng.client.render.items; + import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; @@ -29,6 +30,7 @@ import net.minecraftforge.client.IItemRenderer; import appeng.items.misc.ItemEncodedPattern; + public class ItemEncodedPatternRenderer implements IItemRenderer { @@ -36,14 +38,14 @@ public class ItemEncodedPatternRenderer implements IItemRenderer boolean recursive; @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) + public boolean handleRenderType( ItemStack item, ItemRenderType type ) { boolean isShiftHeld = Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ); - if ( !this.recursive && type == IItemRenderer.ItemRenderType.INVENTORY && isShiftHeld ) + if( !this.recursive && type == IItemRenderer.ItemRenderType.INVENTORY && isShiftHeld ) { ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); - if ( iep.getOutput( item ) != null ) + if( iep.getOutput( item ) != null ) return true; } @@ -51,13 +53,13 @@ public class ItemEncodedPatternRenderer implements IItemRenderer } @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) + public boolean shouldUseRenderHelper( ItemRenderType type, ItemStack item, ItemRendererHelper helper ) { return false; } @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) + public void renderItem( ItemRenderType type, ItemStack item, Object... data ) { this.recursive = true; diff --git a/src/main/java/appeng/client/render/items/PaintBallRender.java b/src/main/java/appeng/client/render/items/PaintBallRender.java index 739e2a8d5..7fd6dc57b 100644 --- a/src/main/java/appeng/client/render/items/PaintBallRender.java +++ b/src/main/java/appeng/client/render/items/PaintBallRender.java @@ -31,26 +31,27 @@ import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; import appeng.items.misc.ItemPaintBall; + public class PaintBallRender implements IItemRenderer { @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) + public boolean handleRenderType( ItemStack item, ItemRenderType type ) { return true; } @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) + public boolean shouldUseRenderHelper( ItemRenderType type, ItemStack item, ItemRendererHelper helper ) { return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; } @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) + public void renderItem( ItemRenderType type, ItemStack item, Object... data ) { IIcon par2Icon = item.getIconIndex(); - if ( item.getItemDamage() >= 20 ) + if( item.getItemDamage() >= 20 ) par2Icon = ExtraItemTextures.ItemPaintBallShimmer.getIcon(); float f4 = par2Icon.getMinU(); @@ -68,19 +69,19 @@ public class PaintBallRender implements IItemRenderer AEColor col = ipb.getColor( item ); int colorValue = item.getItemDamage() >= 20 ? col.mediumVariant : col.mediumVariant; - int r = (colorValue >> 16) & 0xff; - int g = (colorValue >> 8) & 0xff; + int r = ( colorValue >> 16 ) & 0xff; + int g = ( colorValue >> 8 ) & 0xff; int b = ( colorValue ) & 0xff; - int full = (int) (255 * 0.3); + int full = (int) ( 255 * 0.3 ); float fail = 0.7f; - if ( item.getItemDamage() >= 20 ) - GL11.glColor4ub( (byte) (full + r * fail), (byte) (full + g * fail), (byte) (full + b * fail), (byte) 255 ); + if( item.getItemDamage() >= 20 ) + GL11.glColor4ub( (byte) ( full + r * fail ), (byte) ( full + g * fail ), (byte) ( full + b * fail ), (byte) 255 ); else GL11.glColor4ub( (byte) r, (byte) g, (byte) b, (byte) 255 ); - if ( type == ItemRenderType.INVENTORY ) + if( type == ItemRenderType.INVENTORY ) { GL11.glScalef( 16F, 16F, 10F ); GL11.glTranslatef( 0.0F, 1.0F, 0.0F ); @@ -97,7 +98,7 @@ public class PaintBallRender implements IItemRenderer } else { - if ( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) + if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); else GL11.glTranslatef( -0.5F, -0.3F, 0.01F ); diff --git a/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java b/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java index 1f50d0e18..92baeaa63 100644 --- a/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java +++ b/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java @@ -18,7 +18,6 @@ package appeng.client.render.items; -import com.mojang.authlib.GameProfile; import org.lwjgl.opengl.GL11; @@ -28,27 +27,30 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; +import com.mojang.authlib.GameProfile; + import appeng.api.implementations.items.IBiometricCard; import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; + public class ToolBiometricCardRender implements IItemRenderer { @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) + public boolean handleRenderType( ItemStack item, ItemRenderType type ) { return true; } @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) + public boolean shouldUseRenderHelper( ItemRenderType type, ItemStack item, ItemRendererHelper helper ) { return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; } @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) + public void renderItem( ItemRenderType type, ItemStack item, Object... data ) { IIcon par2Icon = item.getIconIndex(); @@ -62,7 +64,7 @@ public class ToolBiometricCardRender implements IItemRenderer GL11.glPushMatrix(); GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - if ( type == ItemRenderType.INVENTORY ) + if( type == ItemRenderType.INVENTORY ) { GL11.glColor4f( 1, 1, 1, 1.0F ); GL11.glScalef( 16F, 16F, 10F ); @@ -94,10 +96,10 @@ public class ToolBiometricCardRender implements IItemRenderer float v = ExtraItemTextures.White.getIcon().getInterpolatedV( 8.1 ); String username = ""; - if ( item.getItem() instanceof IBiometricCard ) + if( item.getItem() instanceof IBiometricCard ) { - GameProfile gp = (( IBiometricCard) item.getItem() ).getProfile(item); - if ( gp != null ) + GameProfile gp = ( (IBiometricCard) item.getItem() ).getProfile( item ); + if( gp != null ) username = gp.getName(); } int hash = username.length() > 0 ? username.hashCode() : 0; @@ -110,26 +112,25 @@ public class ToolBiometricCardRender implements IItemRenderer float z = 0; AEColor col = AEColor.values()[Math.abs( 3 + hash ) % AEColor.values().length]; - if ( hash == 0 ) + if( hash == 0 ) col = AEColor.Black; - for (int x = 0; x < 8; x++)// 8 + for( int x = 0; x < 8; x++ )// 8 { - for (int y = 0; y < 6; y++)// 6 + for( int y = 0; y < 6; y++ )// 6 { boolean isLit = false; float scale = 0.3f / 255.0f; - if ( x == 0 || y == 0 || x == 7 || y == 5 ) + if( x == 0 || y == 0 || x == 7 || y == 5 ) isLit = false; else - isLit = (hash & (1 << x)) != 0 || (hash & (1 << y)) != 0; + isLit = ( hash & ( 1 << x ) ) != 0 || ( hash & ( 1 << y ) ) != 0; - if ( isLit ) + if( isLit ) tessellator.setColorOpaque_I( col.mediumVariant ); else - tessellator.setColorOpaque_F( ((col.blackVariant >> 16) & 0xff) * scale, ((col.blackVariant >> 8) & 0xff) * scale, - (col.blackVariant & 0xff) * scale ); + tessellator.setColorOpaque_F( ( ( col.blackVariant >> 16 ) & 0xff ) * scale, ( ( col.blackVariant >> 8 ) & 0xff ) * scale, ( col.blackVariant & 0xff ) * scale ); tessellator.addVertexWithUV( x, y, z, u, v ); tessellator.addVertexWithUV( x + 1, y, z, u, v ); diff --git a/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java b/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java index 1c27784e4..d9e9bc73f 100644 --- a/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java +++ b/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java @@ -18,6 +18,7 @@ package appeng.client.render.items; + import org.lwjgl.opengl.GL11; import net.minecraft.client.renderer.ItemRenderer; @@ -30,23 +31,24 @@ import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; import appeng.items.tools.powered.ToolColorApplicator; + public class ToolColorApplicatorRender implements IItemRenderer { @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) + public boolean handleRenderType( ItemStack item, ItemRenderType type ) { return true; } @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) + public boolean shouldUseRenderHelper( ItemRenderType type, ItemStack item, ItemRendererHelper helper ) { return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; } @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) + public void renderItem( ItemRenderType type, ItemStack item, Object... data ) { IIcon par2Icon = item.getIconIndex(); @@ -60,7 +62,7 @@ public class ToolColorApplicatorRender implements IItemRenderer GL11.glPushMatrix(); GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - if ( type == ItemRenderType.INVENTORY ) + if( type == ItemRenderType.INVENTORY ) { GL11.glColor4f( 1, 1, 1, 1.0F ); GL11.glScalef( 16F, 16F, 10F ); @@ -78,9 +80,9 @@ public class ToolColorApplicatorRender implements IItemRenderer } else { - if ( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) + if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); - else if ( type == ItemRenderType.EQUIPPED ) + else if( type == ItemRenderType.EQUIPPED ) GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); else GL11.glTranslatef( -0.5F, -0.3F, 0.01F ); @@ -98,15 +100,15 @@ public class ToolColorApplicatorRender implements IItemRenderer IIcon light = ExtraItemTextures.ToolColorApplicatorTip_Light.getIcon(); GL11.glScalef( 1F / 16F, 1F / 16F, 1F ); - if ( type != ItemRenderType.INVENTORY ) + if( type != ItemRenderType.INVENTORY ) GL11.glTranslatef( 2, 0, 0 ); GL11.glDisable( GL11.GL_LIGHTING ); AEColor col = null; - col = ((ToolColorApplicator) item.getItem()).getActiveColor( item ); + col = ( (ToolColorApplicator) item.getItem() ).getActiveColor( item ); - if ( col != null ) + if( col != null ) { tessellator.startDrawingQuads(); diff --git a/src/main/java/appeng/client/render/model/ModelCompass.java b/src/main/java/appeng/client/render/model/ModelCompass.java index 70de95b87..92d28aad0 100644 --- a/src/main/java/appeng/client/render/model/ModelCompass.java +++ b/src/main/java/appeng/client/render/model/ModelCompass.java @@ -18,9 +18,11 @@ package appeng.client.render.model; + import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; + public class ModelCompass extends ModelBase { @@ -33,7 +35,8 @@ public class ModelCompass extends ModelBase final ModelRenderer Pointer; - public ModelCompass() { + public ModelCompass() + { this.textureWidth = 16; this.textureHeight = 8; @@ -90,14 +93,14 @@ public class ModelCompass extends ModelBase this.setRotation( this.Base, 0F, 0F, 0F ); } - private void setRotation(ModelRenderer model, float x, float y, float z) + private void setRotation( ModelRenderer model, float x, float y, float z ) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } - public void renderAll(float rad) + public void renderAll( float rad ) { this.setRotation( this.Pointer, 0F, 0F, 0F ); diff --git a/src/main/java/appeng/client/texture/CableBusTextures.java b/src/main/java/appeng/client/texture/CableBusTextures.java index 4191cc019..4f712df93 100644 --- a/src/main/java/appeng/client/texture/CableBusTextures.java +++ b/src/main/java/appeng/client/texture/CableBusTextures.java @@ -18,6 +18,7 @@ package appeng.client.texture; + import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; @@ -26,98 +27,85 @@ import net.minecraft.util.ResourceLocation; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + public enum CableBusTextures { - Channels00("MECableSmart00"), Channels01("MECableSmart01"), Channels02("MECableSmart02"), Channels03("MECableSmart03"), Channels10("MECableSmart10"), Channels11( - "MECableSmart11"), Channels12("MECableSmart12"), Channels13("MECableSmart13"), Channels14("MECableSmart14"), Channels04("MECableSmart04"), + Channels00( "MECableSmart00" ), Channels01( "MECableSmart01" ), Channels02( "MECableSmart02" ), Channels03( "MECableSmart03" ), Channels10( "MECableSmart10" ), Channels11( "MECableSmart11" ), Channels12( "MECableSmart12" ), Channels13( "MECableSmart13" ), Channels14( "MECableSmart14" ), Channels04( "MECableSmart04" ), - LevelEmitterTorchOn("ItemPart.LevelEmitterOn"), BlockWirelessOn("BlockWirelessOn"), + LevelEmitterTorchOn( "ItemPart.LevelEmitterOn" ), BlockWirelessOn( "BlockWirelessOn" ), - BlockP2PTunnel2("ItemPart.P2PTunnel2"), BlockP2PTunnel3("ItemPart.P2PTunnel3"), + BlockP2PTunnel2( "ItemPart.P2PTunnel2" ), BlockP2PTunnel3( "ItemPart.P2PTunnel3" ), // MEWaiting("MEWaiting"), - PartMonitorSides("PartMonitorSides"), PartMonitorBack("PartMonitorBack"), + PartMonitorSides( "PartMonitorSides" ), PartMonitorBack( "PartMonitorBack" ), - Transparent("Transparent"), PartMonitorSidesStatus("PartMonitorSidesStatus"), PartMonitorSidesStatusLights("PartMonitorSidesStatusLights"), + Transparent( "Transparent" ), PartMonitorSidesStatus( "PartMonitorSidesStatus" ), PartMonitorSidesStatusLights( "PartMonitorSidesStatusLights" ), - PartMonitor_Colored("PartMonitor_Colored"), PartMonitor_Bright("PartMonitor_Bright"), + PartMonitor_Colored( "PartMonitor_Colored" ), PartMonitor_Bright( "PartMonitor_Bright" ), - PartPatternTerm_Bright("PartPatternTerm_Bright"), PartPatternTerm_Colored("PartPatternTerm_Colored"), PartPatternTerm_Dark("PartPatternTerm_Dark"), + PartPatternTerm_Bright( "PartPatternTerm_Bright" ), PartPatternTerm_Colored( "PartPatternTerm_Colored" ), PartPatternTerm_Dark( "PartPatternTerm_Dark" ), - PartConversionMonitor_Bright("PartConversionMonitor_Bright"), PartConversionMonitor_Colored("PartConversionMonitor_Colored"), PartConversionMonitor_Dark("PartConversionMonitor_Dark"), + PartConversionMonitor_Bright( "PartConversionMonitor_Bright" ), PartConversionMonitor_Colored( "PartConversionMonitor_Colored" ), PartConversionMonitor_Dark( "PartConversionMonitor_Dark" ), - PartInterfaceTerm_Bright("PartInterfaceTerm_Bright"), PartInterfaceTerm_Colored("PartInterfaceTerm_Colored"), PartInterfaceTerm_Dark( - "PartInterfaceTerm_Dark"), + PartInterfaceTerm_Bright( "PartInterfaceTerm_Bright" ), PartInterfaceTerm_Colored( "PartInterfaceTerm_Colored" ), PartInterfaceTerm_Dark( "PartInterfaceTerm_Dark" ), - PartCraftingTerm_Bright("PartCraftingTerm_Bright"), PartCraftingTerm_Colored("PartCraftingTerm_Colored"), PartCraftingTerm_Dark("PartCraftingTerm_Dark"), // + PartCraftingTerm_Bright( "PartCraftingTerm_Bright" ), PartCraftingTerm_Colored( "PartCraftingTerm_Colored" ), PartCraftingTerm_Dark( "PartCraftingTerm_Dark" ), // - PartStorageMonitor_Bright("PartStorageMonitor_Bright"), PartStorageMonitor_Colored("PartStorageMonitor_Colored"), PartStorageMonitor_Dark( - "PartStorageMonitor_Dark"), + PartStorageMonitor_Bright( "PartStorageMonitor_Bright" ), PartStorageMonitor_Colored( "PartStorageMonitor_Colored" ), PartStorageMonitor_Dark( "PartStorageMonitor_Dark" ), - PartTerminal_Bright("PartTerminal_Bright"), PartTerminal_Colored("PartTerminal_Colored"), PartTerminal_Dark("PartTerminal_Dark"), + PartTerminal_Bright( "PartTerminal_Bright" ), PartTerminal_Colored( "PartTerminal_Colored" ), PartTerminal_Dark( "PartTerminal_Dark" ), - MECable_Green("MECable_Green"), MECable_Grey("MECable_Grey"), MECable_LightBlue("MECable_LightBlue"), MECable_LightGrey("MECable_LightGrey"), MECable_Lime( - "MECable_Lime"), MECable_Magenta("MECable_Magenta"), MECable_Orange("MECable_Orange"), MECable_Pink("MECable_Pink"), MECable_Purple( - "MECable_Purple"), MECable_Red("MECable_Red"), MECable_White("MECable_White"), MECable_Yellow("MECable_Yellow"), MECable_Black("MECable_Black"), MECable_Blue( - "MECable_Blue"), MECable_Brown("MECable_Brown"), MECable_Cyan("MECable_Cyan"), + MECable_Green( "MECable_Green" ), MECable_Grey( "MECable_Grey" ), MECable_LightBlue( "MECable_LightBlue" ), MECable_LightGrey( "MECable_LightGrey" ), MECable_Lime( "MECable_Lime" ), MECable_Magenta( "MECable_Magenta" ), MECable_Orange( "MECable_Orange" ), MECable_Pink( "MECable_Pink" ), MECable_Purple( "MECable_Purple" ), MECable_Red( "MECable_Red" ), MECable_White( "MECable_White" ), MECable_Yellow( "MECable_Yellow" ), MECable_Black( "MECable_Black" ), MECable_Blue( "MECable_Blue" ), MECable_Brown( "MECable_Brown" ), MECable_Cyan( "MECable_Cyan" ), - MEDense_Black("MEDense_Black"), MEDense_Blue("MEDense_Blue"), MEDense_Brown("MEDense_Brown"), MEDense_Cyan("MEDense_Cyan"), MEDense_Gray("MEDense_Gray"), MEDense_Green( - "MEDense_Green"), MEDense_LightBlue("MEDense_LightBlue"), MEDense_LightGrey("MEDense_LightGrey"), MEDense_Lime("MEDense_Lime"), MEDense_Magenta( - "MEDense_Magenta"), MEDense_Orange("MEDense_Orange"), MEDense_Pink("MEDense_Pink"), MEDense_Purple("MEDense_Purple"), MEDense_Red("MEDense_Red"), MEDense_White( - "MEDense_White"), MEDense_Yellow("MEDense_Yellow"), + MEDense_Black( "MEDense_Black" ), MEDense_Blue( "MEDense_Blue" ), MEDense_Brown( "MEDense_Brown" ), MEDense_Cyan( "MEDense_Cyan" ), MEDense_Gray( "MEDense_Gray" ), MEDense_Green( "MEDense_Green" ), MEDense_LightBlue( "MEDense_LightBlue" ), MEDense_LightGrey( "MEDense_LightGrey" ), MEDense_Lime( "MEDense_Lime" ), MEDense_Magenta( "MEDense_Magenta" ), MEDense_Orange( "MEDense_Orange" ), MEDense_Pink( "MEDense_Pink" ), MEDense_Purple( "MEDense_Purple" ), MEDense_Red( "MEDense_Red" ), MEDense_White( "MEDense_White" ), MEDense_Yellow( "MEDense_Yellow" ), - MESmart_Black("MESmart_Black"), MESmart_Blue("MESmart_Blue"), MESmart_Brown("MESmart_Brown"), MESmart_Cyan("MESmart_Cyan"), MESmart_Gray("MESmart_Gray"), MESmart_Green( - "MESmart_Green"), MESmart_LightBlue("MESmart_LightBlue"), MESmart_LightGrey("MESmart_LightGrey"), MESmart_Lime("MESmart_Lime"), MESmart_Magenta( - "MESmart_Magenta"), MESmart_Orange("MESmart_Orange"), MESmart_Pink("MESmart_Pink"), MESmart_Purple("MESmart_Purple"), MESmart_Red("MESmart_Red"), MESmart_White( - "MESmart_White"), MESmart_Yellow("MESmart_Yellow"), + MESmart_Black( "MESmart_Black" ), MESmart_Blue( "MESmart_Blue" ), MESmart_Brown( "MESmart_Brown" ), MESmart_Cyan( "MESmart_Cyan" ), MESmart_Gray( "MESmart_Gray" ), MESmart_Green( "MESmart_Green" ), MESmart_LightBlue( "MESmart_LightBlue" ), MESmart_LightGrey( "MESmart_LightGrey" ), MESmart_Lime( "MESmart_Lime" ), MESmart_Magenta( "MESmart_Magenta" ), MESmart_Orange( "MESmart_Orange" ), MESmart_Pink( "MESmart_Pink" ), MESmart_Purple( "MESmart_Purple" ), MESmart_Red( "MESmart_Red" ), MESmart_White( "MESmart_White" ), MESmart_Yellow( "MESmart_Yellow" ), - MECovered_Black("MECovered_Black"), MECovered_Blue("MECovered_Blue"), MECovered_Brown("MECovered_Brown"), MECovered_Cyan("MECovered_Cyan"), MECovered_Gray( - "MECovered_Gray"), MECovered_Green("MECovered_Green"), MECovered_LightBlue("MECovered_LightBlue"), MECovered_LightGrey("MECovered_LightGrey"), MECovered_Lime( - "MECovered_Lime"), MECovered_Magenta("MECovered_Magenta"), MECovered_Orange("MECovered_Orange"), MECovered_Pink("MECovered_Pink"), MECovered_Purple( - "MECovered_Purple"), MECovered_Red("MECovered_Red"), MECovered_White("MECovered_White"), MECovered_Yellow("MECovered_Yellow"), + MECovered_Black( "MECovered_Black" ), MECovered_Blue( "MECovered_Blue" ), MECovered_Brown( "MECovered_Brown" ), MECovered_Cyan( "MECovered_Cyan" ), MECovered_Gray( "MECovered_Gray" ), MECovered_Green( "MECovered_Green" ), MECovered_LightBlue( "MECovered_LightBlue" ), MECovered_LightGrey( "MECovered_LightGrey" ), MECovered_Lime( "MECovered_Lime" ), MECovered_Magenta( "MECovered_Magenta" ), MECovered_Orange( "MECovered_Orange" ), MECovered_Pink( "MECovered_Pink" ), MECovered_Purple( "MECovered_Purple" ), MECovered_Red( "MECovered_Red" ), MECovered_White( "MECovered_White" ), MECovered_Yellow( "MECovered_Yellow" ), - BlockAnnihilationPlaneOn("BlockAnnihilationPlaneOn"), + BlockAnnihilationPlaneOn( "BlockAnnihilationPlaneOn" ), - BlockFormPlaneOn("BlockFormPlaneOn"), + BlockFormPlaneOn( "BlockFormPlaneOn" ), - ItemPartLevelEmitterOn("ItemPart.LevelEmitterOn"), PartTransitionPlaneBack("PartTransitionPlaneBack"), + ItemPartLevelEmitterOn( "ItemPart.LevelEmitterOn" ), PartTransitionPlaneBack( "PartTransitionPlaneBack" ), - PartTunnelSides("PartTunnelSides"), PartPlaneSides("PartPlaneSides"), PartExportSides("PartExportSides"), PartImportSides("PartImportSides"), + PartTunnelSides( "PartTunnelSides" ), PartPlaneSides( "PartPlaneSides" ), PartExportSides( "PartExportSides" ), PartImportSides( "PartImportSides" ), - PartWirelessSides("PartWirelessSides"), PartStorageSides("PartStorageSides"), PartStorageBack("PartStorageBack"); + PartWirelessSides( "PartWirelessSides" ), PartStorageSides( "PartStorageSides" ), PartStorageBack( "PartStorageBack" ); final private String name; public IIcon IIcon; - public static ResourceLocation GuiTexture(String string) + CableBusTextures( String name ) + { + this.name = name; + } + + public static ResourceLocation GuiTexture( String string ) { return null; } + @SideOnly( Side.CLIENT ) + public static IIcon getMissing() + { + return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationBlocksTexture ) ).getAtlasSprite( "missingno" ); + } + public String getName() { return this.name; } - CableBusTextures( String name ) { - this.name = name; - } - public IIcon getIcon() { return this.IIcon; } - public void registerIcon(TextureMap map) + public void registerIcon( TextureMap map ) { this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); } - - @SideOnly(Side.CLIENT) - public static IIcon getMissing() - { - return ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationBlocksTexture )).getAtlasSprite( "missingno" ); - } } diff --git a/src/main/java/appeng/client/texture/ExtraBlockTextures.java b/src/main/java/appeng/client/texture/ExtraBlockTextures.java index 27944d195..34a50b7b0 100644 --- a/src/main/java/appeng/client/texture/ExtraBlockTextures.java +++ b/src/main/java/appeng/client/texture/ExtraBlockTextures.java @@ -18,6 +18,7 @@ package appeng.client.texture; + import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; @@ -26,108 +27,98 @@ import net.minecraft.util.ResourceLocation; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + public enum ExtraBlockTextures { - BlockVibrationChamberFrontOn("BlockVibrationChamberFrontOn"), + BlockVibrationChamberFrontOn( "BlockVibrationChamberFrontOn" ), - OreQuartzStone("OreQuartzStone"), + OreQuartzStone( "OreQuartzStone" ), - MEChest("BlockMEChest"), + MEChest( "BlockMEChest" ), - BlockMEChestItems_Light("BlockMEChestItems_Light"), BlockMEChestItems_Dark("BlockMEChestItems_Dark"), BlockMEChestItems_Medium("BlockMEChestItems_Medium"), + BlockMEChestItems_Light( "BlockMEChestItems_Light" ), BlockMEChestItems_Dark( "BlockMEChestItems_Dark" ), BlockMEChestItems_Medium( "BlockMEChestItems_Medium" ), - BlockControllerPowered("BlockControllerPowered"), BlockControllerColumnPowered("BlockControllerColumnPowered"), BlockControllerColumn( - "BlockControllerColumn"), BlockControllerLights("BlockControllerLights"), BlockControllerColumnLights("BlockControllerColumnLights"), BlockControllerColumnConflict( - "BlockControllerColumnConflict"), BlockControllerConflict("BlockControllerConflict"), BlockControllerInsideA("BlockControllerInsideA"), BlockControllerInsideB( - "BlockControllerInsideB"), + BlockControllerPowered( "BlockControllerPowered" ), BlockControllerColumnPowered( "BlockControllerColumnPowered" ), BlockControllerColumn( "BlockControllerColumn" ), BlockControllerLights( "BlockControllerLights" ), BlockControllerColumnLights( "BlockControllerColumnLights" ), BlockControllerColumnConflict( "BlockControllerColumnConflict" ), BlockControllerConflict( "BlockControllerConflict" ), BlockControllerInsideA( "BlockControllerInsideA" ), BlockControllerInsideB( "BlockControllerInsideB" ), - BlockMolecularAssemblerLights("BlockMolecularAssemblerLights"), + BlockMolecularAssemblerLights( "BlockMolecularAssemblerLights" ), - BlockChargerInside("BlockChargerInside"), + BlockChargerInside( "BlockChargerInside" ), - BlockInterfaceAlternate("BlockInterfaceAlternate"), BlockInterfaceAlternateArrow("BlockInterfaceAlternateArrow"), + BlockInterfaceAlternate( "BlockInterfaceAlternate" ), BlockInterfaceAlternateArrow( "BlockInterfaceAlternateArrow" ), - MEStorageCellTextures("MEStorageCellTextures"), White("White"), + MEStorageCellTextures( "MEStorageCellTextures" ), White( "White" ), - BlockMatterCannonParticle("BlockMatterCannonParticle"), BlockEnergyParticle("BlockEnergyParticle"), + BlockMatterCannonParticle( "BlockMatterCannonParticle" ), BlockEnergyParticle( "BlockEnergyParticle" ), - GlassFrame("BlockQuartzGlassFrame"), + GlassFrame( "BlockQuartzGlassFrame" ), - BlockQRingCornerLight("BlockQRingCornerLight"), BlockQRingEdgeLight("BlockQRingEdgeLight"), + BlockQRingCornerLight( "BlockQRingCornerLight" ), BlockQRingEdgeLight( "BlockQRingEdgeLight" ), - MEDenseEnergyCell0("BlockDenseEnergyCell0"), MEDenseEnergyCell1("BlockDenseEnergyCell1"), MEDenseEnergyCell2("BlockDenseEnergyCell2"), MEDenseEnergyCell3( - "BlockDenseEnergyCell3"), MEDenseEnergyCell4("BlockDenseEnergyCell4"), MEDenseEnergyCell5("BlockDenseEnergyCell5"), MEDenseEnergyCell6( - "BlockDenseEnergyCell6"), MEDenseEnergyCell7("BlockDenseEnergyCell7"), + MEDenseEnergyCell0( "BlockDenseEnergyCell0" ), MEDenseEnergyCell1( "BlockDenseEnergyCell1" ), MEDenseEnergyCell2( "BlockDenseEnergyCell2" ), MEDenseEnergyCell3( "BlockDenseEnergyCell3" ), MEDenseEnergyCell4( "BlockDenseEnergyCell4" ), MEDenseEnergyCell5( "BlockDenseEnergyCell5" ), MEDenseEnergyCell6( "BlockDenseEnergyCell6" ), MEDenseEnergyCell7( "BlockDenseEnergyCell7" ), - MEEnergyCell0("BlockEnergyCell0"), MEEnergyCell1("BlockEnergyCell1"), MEEnergyCell2("BlockEnergyCell2"), MEEnergyCell3("BlockEnergyCell3"), MEEnergyCell4( - "BlockEnergyCell4"), MEEnergyCell5("BlockEnergyCell5"), MEEnergyCell6("BlockEnergyCell6"), MEEnergyCell7("BlockEnergyCell7"), + MEEnergyCell0( "BlockEnergyCell0" ), MEEnergyCell1( "BlockEnergyCell1" ), MEEnergyCell2( "BlockEnergyCell2" ), MEEnergyCell3( "BlockEnergyCell3" ), MEEnergyCell4( "BlockEnergyCell4" ), MEEnergyCell5( "BlockEnergyCell5" ), MEEnergyCell6( "BlockEnergyCell6" ), MEEnergyCell7( "BlockEnergyCell7" ), - BlockSpatialPylon_dim("BlockSpatialPylon_dim"), BlockSpatialPylon_red("BlockSpatialPylon_red"), + BlockSpatialPylon_dim( "BlockSpatialPylon_dim" ), BlockSpatialPylon_red( "BlockSpatialPylon_red" ), - BlockSpatialPylonC("BlockSpatialPylon_spanned"), BlockSpatialPylonC_dim("BlockSpatialPylon_spanned_dim"), BlockSpatialPylonC_red( - "BlockSpatialPylon_spanned_red"), + BlockSpatialPylonC( "BlockSpatialPylon_spanned" ), BlockSpatialPylonC_dim( "BlockSpatialPylon_spanned_dim" ), BlockSpatialPylonC_red( "BlockSpatialPylon_spanned_red" ), - BlockQuartzGlassB("BlockQuartzGlassB"), BlockQuartzGlassC("BlockQuartzGlassC"), BlockQuartzGlassD("BlockQuartzGlassD"), + BlockQuartzGlassB( "BlockQuartzGlassB" ), BlockQuartzGlassC( "BlockQuartzGlassC" ), BlockQuartzGlassD( "BlockQuartzGlassD" ), - BlockSpatialPylonE("BlockSpatialPylon_end"), BlockSpatialPylonE_dim("BlockSpatialPylon_end_dim"), BlockSpatialPylonE_red("BlockSpatialPylon_end_red"), + BlockSpatialPylonE( "BlockSpatialPylon_end" ), BlockSpatialPylonE_dim( "BlockSpatialPylon_end_dim" ), BlockSpatialPylonE_red( "BlockSpatialPylon_end_red" ), - BlockMESecurityOn_Light("BlockMESecurityOn_Light"), BlockMESecurityOn_Medium("BlockMESecurityOn_Medium"), BlockMESecurityOn_Dark("BlockMESecurityOn_Dark"), BlockInscriberInside( - "BlockInscriberInside"), + BlockMESecurityOn_Light( "BlockMESecurityOn_Light" ), BlockMESecurityOn_Medium( "BlockMESecurityOn_Medium" ), BlockMESecurityOn_Dark( "BlockMESecurityOn_Dark" ), BlockInscriberInside( "BlockInscriberInside" ), - BlockQuartzGrowthAcceleratorOn("BlockQuartzGrowthAcceleratorOn"), BlockQuartzGrowthAcceleratorSideOn("BlockQuartzGrowthAcceleratorSideOn"), + BlockQuartzGrowthAcceleratorOn( "BlockQuartzGrowthAcceleratorOn" ), BlockQuartzGrowthAcceleratorSideOn( "BlockQuartzGrowthAcceleratorSideOn" ), - BlockWirelessInside("BlockWirelessInside"), + BlockWirelessInside( "BlockWirelessInside" ), - BlockCraftingAccelerator("BlockCraftingAccelerator"), BlockCraftingMonitor("BlockCraftingMonitor"), + BlockCraftingAccelerator( "BlockCraftingAccelerator" ), BlockCraftingMonitor( "BlockCraftingMonitor" ), - BlockCraftingStorage1k("BlockCraftingStorage"), BlockCraftingStorage4k("BlockCraftingStorage4k"), BlockCraftingStorage16k("BlockCraftingStorage16k"), BlockCraftingStorage64k( - "BlockCraftingStorage64k"), + BlockCraftingStorage1k( "BlockCraftingStorage" ), BlockCraftingStorage4k( "BlockCraftingStorage4k" ), BlockCraftingStorage16k( "BlockCraftingStorage16k" ), BlockCraftingStorage64k( "BlockCraftingStorage64k" ), - BlockCraftingAcceleratorFit("BlockCraftingAcceleratorFit"), + BlockCraftingAcceleratorFit( "BlockCraftingAcceleratorFit" ), - BlockCraftingMonitorFit_Light("BlockCraftingMonitorFit_Light"), BlockCraftingMonitorFit_Dark("BlockCraftingMonitorFit_Dark"), BlockCraftingMonitorFit_Medium( - "BlockCraftingMonitorFit_Medium"), + BlockCraftingMonitorFit_Light( "BlockCraftingMonitorFit_Light" ), BlockCraftingMonitorFit_Dark( "BlockCraftingMonitorFit_Dark" ), BlockCraftingMonitorFit_Medium( "BlockCraftingMonitorFit_Medium" ), - BlockCraftingStorage1kFit("BlockCraftingStorageFit"), BlockCraftingStorage4kFit("BlockCraftingStorage4kFit"), BlockCraftingStorage16kFit( - "BlockCraftingStorage16kFit"), BlockCraftingStorage64kFit("BlockCraftingStorage64kFit"), + BlockCraftingStorage1kFit( "BlockCraftingStorageFit" ), BlockCraftingStorage4kFit( "BlockCraftingStorage4kFit" ), BlockCraftingStorage16kFit( "BlockCraftingStorage16kFit" ), BlockCraftingStorage64kFit( "BlockCraftingStorage64kFit" ), - BlockCraftingUnitRing("BlockCraftingUnitRing"), BlockCraftingUnitRingLongRotated("BlockCraftingUnitRingLongRotated"), BlockCraftingUnitRingLong( - "BlockCraftingUnitRingLong"), BlockCraftingUnitFit("BlockCraftingUnitFit"), + BlockCraftingUnitRing( "BlockCraftingUnitRing" ), BlockCraftingUnitRingLongRotated( "BlockCraftingUnitRingLongRotated" ), BlockCraftingUnitRingLong( "BlockCraftingUnitRingLong" ), BlockCraftingUnitFit( "BlockCraftingUnitFit" ), - BlockCraftingMonitorOuter("BlockCraftingMonitorOuter"), BlockCraftingFitSolid("BlockCraftingFitSolid"), + BlockCraftingMonitorOuter( "BlockCraftingMonitorOuter" ), BlockCraftingFitSolid( "BlockCraftingFitSolid" ), - BlockPaint2("BlockPaint2"), BlockPaint3("BlockPaint3"); + BlockPaint2( "BlockPaint2" ), BlockPaint3( "BlockPaint3" ); final private String name; public IIcon IIcon; - public static ResourceLocation GuiTexture(String string) + ExtraBlockTextures( String name ) + { + this.name = name; + } + + public static ResourceLocation GuiTexture( String string ) { return new ResourceLocation( "appliedenergistics2", "textures/" + string ); } + @SideOnly( Side.CLIENT ) + public static IIcon getMissing() + { + return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationBlocksTexture ) ).getAtlasSprite( "missingno" ); + } + public String getName() { return this.name; } - ExtraBlockTextures( String name ) { - this.name = name; - } - public IIcon getIcon() { return this.IIcon; } - public void registerIcon(TextureMap map) + public void registerIcon( TextureMap map ) { this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); } - - @SideOnly(Side.CLIENT) - public static IIcon getMissing() - { - return ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationBlocksTexture )).getAtlasSprite( "missingno" ); - } } diff --git a/src/main/java/appeng/client/texture/ExtraItemTextures.java b/src/main/java/appeng/client/texture/ExtraItemTextures.java index 1fb788f35..3794b65c8 100644 --- a/src/main/java/appeng/client/texture/ExtraItemTextures.java +++ b/src/main/java/appeng/client/texture/ExtraItemTextures.java @@ -18,6 +18,7 @@ package appeng.client.texture; + import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; @@ -26,46 +27,48 @@ import net.minecraft.util.ResourceLocation; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + public enum ExtraItemTextures { - White("White"), ItemPaintBallShimmer("ItemPaintBallShimmer"), + White( "White" ), ItemPaintBallShimmer( "ItemPaintBallShimmer" ), - ToolColorApplicatorTip_Medium("ToolColorApplicatorTip_Medium"), + ToolColorApplicatorTip_Medium( "ToolColorApplicatorTip_Medium" ), - ToolColorApplicatorTip_Dark("ToolColorApplicatorTip_Dark"), + ToolColorApplicatorTip_Dark( "ToolColorApplicatorTip_Dark" ), - ToolColorApplicatorTip_Light("ToolColorApplicatorTip_Light"); + ToolColorApplicatorTip_Light( "ToolColorApplicatorTip_Light" ); final private String name; public IIcon IIcon; - public static ResourceLocation GuiTexture(String string) + ExtraItemTextures( String name ) + { + this.name = name; + } + + public static ResourceLocation GuiTexture( String string ) { return new ResourceLocation( "appliedenergistics2", "textures/" + string ); } + @SideOnly( Side.CLIENT ) + public static IIcon getMissing() + { + return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationItemsTexture ) ).getAtlasSprite( "missingno" ); + } + public String getName() { return this.name; } - ExtraItemTextures( String name ) { - this.name = name; - } - public IIcon getIcon() { return this.IIcon; } - public void registerIcon(TextureMap map) + public void registerIcon( TextureMap map ) { this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); } - - @SideOnly(Side.CLIENT) - public static IIcon getMissing() - { - return ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationItemsTexture )).getAtlasSprite( "missingno" ); - } } diff --git a/src/main/java/appeng/client/texture/FlippableIcon.java b/src/main/java/appeng/client/texture/FlippableIcon.java index 2f45ce1ca..aa2aee330 100644 --- a/src/main/java/appeng/client/texture/FlippableIcon.java +++ b/src/main/java/appeng/client/texture/FlippableIcon.java @@ -18,8 +18,10 @@ package appeng.client.texture; + import net.minecraft.util.IIcon; + public class FlippableIcon implements IIcon { @@ -27,9 +29,10 @@ public class FlippableIcon implements IIcon boolean flip_u; boolean flip_v; - public FlippableIcon(IIcon o) { + public FlippableIcon( IIcon o ) + { - if ( o == null ) + if( o == null ) throw new RuntimeException( "Cannot create a wrapper icon with a null icon." ); this.original = o; @@ -52,7 +55,7 @@ public class FlippableIcon implements IIcon @Override public float getMinU() { - if ( this.flip_u ) + if( this.flip_u ) return this.original.getMaxU(); return this.original.getMinU(); } @@ -60,15 +63,15 @@ public class FlippableIcon implements IIcon @Override public float getMaxU() { - if ( this.flip_u ) + if( this.flip_u ) return this.original.getMinU(); return this.original.getMaxU(); } @Override - public float getInterpolatedU(double px) + public float getInterpolatedU( double px ) { - if ( this.flip_u ) + if( this.flip_u ) return this.original.getInterpolatedU( 16 - px ); return this.original.getInterpolatedU( px ); } @@ -76,7 +79,7 @@ public class FlippableIcon implements IIcon @Override public float getMinV() { - if ( this.flip_v ) + if( this.flip_v ) return this.original.getMaxV(); return this.original.getMinV(); } @@ -84,15 +87,15 @@ public class FlippableIcon implements IIcon @Override public float getMaxV() { - if ( this.flip_v ) + if( this.flip_v ) return this.original.getMinV(); return this.original.getMaxV(); } @Override - public float getInterpolatedV(double px) + public float getInterpolatedV( double px ) { - if ( this.flip_v ) + if( this.flip_v ) return this.original.getInterpolatedV( 16 - px ); return this.original.getInterpolatedV( px ); } @@ -108,17 +111,16 @@ public class FlippableIcon implements IIcon return this.original; } - public void setFlip(boolean u, boolean v) + public void setFlip( boolean u, boolean v ) { this.flip_u = u; this.flip_v = v; } - public int setFlip(int orientation) + public int setFlip( int orientation ) { - this.flip_u = (orientation & 8) == 8; - this.flip_v = (orientation & 16) == 16; + this.flip_u = ( orientation & 8 ) == 8; + this.flip_v = ( orientation & 16 ) == 16; return orientation & 7; } - } diff --git a/src/main/java/appeng/client/texture/FullIcon.java b/src/main/java/appeng/client/texture/FullIcon.java index e4adb764d..ea289f1f7 100644 --- a/src/main/java/appeng/client/texture/FullIcon.java +++ b/src/main/java/appeng/client/texture/FullIcon.java @@ -18,77 +18,27 @@ package appeng.client.texture; + import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + public class FullIcon implements IIcon { private final IIcon p; - public FullIcon(IIcon o) { + public FullIcon( IIcon o ) + { - if ( o == null ) - throw new RuntimeException("Cannot create a wrapper icon with a null icon."); + if( o == null ) + throw new RuntimeException( "Cannot create a wrapper icon with a null icon." ); this.p = o; } - @Override - @SideOnly(Side.CLIENT) - public float getMinU() - { - return this.p.getMinU(); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMaxU() - { - return this.p.getMaxU(); - } - - @Override - @SideOnly(Side.CLIENT) - public float getInterpolatedU(double d0) - { - if ( d0 > 8.0 ) - return this.p.getMaxU(); - return this.p.getMinU(); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMinV() - { - return this.p.getMinV(); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMaxV() - { - return this.p.getMaxV(); - } - - @Override - @SideOnly(Side.CLIENT) - public float getInterpolatedV(double d0) - { - if ( d0 > 8.0 ) - return this.p.getMaxV(); - return this.p.getMinV(); - } - - @Override - @SideOnly(Side.CLIENT) - public String getIconName() - { - return this.p.getIconName(); - } - @Override public int getIconWidth() { @@ -101,4 +51,56 @@ public class FullIcon implements IIcon return this.p.getIconHeight(); } + @Override + @SideOnly( Side.CLIENT ) + public float getMinU() + { + return this.p.getMinU(); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMaxU() + { + return this.p.getMaxU(); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getInterpolatedU( double d0 ) + { + if( d0 > 8.0 ) + return this.p.getMaxU(); + return this.p.getMinU(); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMinV() + { + return this.p.getMinV(); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMaxV() + { + return this.p.getMaxV(); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getInterpolatedV( double d0 ) + { + if( d0 > 8.0 ) + return this.p.getMaxV(); + return this.p.getMinV(); + } + + @Override + @SideOnly( Side.CLIENT ) + public String getIconName() + { + return this.p.getIconName(); + } } diff --git a/src/main/java/appeng/client/texture/MissingIcon.java b/src/main/java/appeng/client/texture/MissingIcon.java index a43b2a4dc..3b8541e86 100644 --- a/src/main/java/appeng/client/texture/MissingIcon.java +++ b/src/main/java/appeng/client/texture/MissingIcon.java @@ -18,6 +18,7 @@ package appeng.client.texture; + import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; @@ -26,20 +27,15 @@ import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + public class MissingIcon implements IIcon { final boolean isBlock; - public MissingIcon(Object forWhat) { - this.isBlock = forWhat instanceof Block; - } - - @SideOnly(Side.CLIENT) - public IIcon getMissing() + public MissingIcon( Object forWhat ) { - return ((TextureMap) Minecraft.getMinecraft().getTextureManager() - .getTexture( this.isBlock ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture )).getAtlasSprite( "missingno" ); + this.isBlock = forWhat instanceof Block; } @Override @@ -48,6 +44,12 @@ public class MissingIcon implements IIcon return this.getMissing().getIconWidth(); } + @SideOnly( Side.CLIENT ) + public IIcon getMissing() + { + return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( this.isBlock ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture ) ).getAtlasSprite( "missingno" ); + } + @Override public int getIconHeight() { @@ -67,7 +69,7 @@ public class MissingIcon implements IIcon } @Override - public float getInterpolatedU(double var1) + public float getInterpolatedU( double var1 ) { return this.getMissing().getInterpolatedU( var1 ); } @@ -85,7 +87,7 @@ public class MissingIcon implements IIcon } @Override - public float getInterpolatedV(double var1) + public float getInterpolatedV( double var1 ) { return this.getMissing().getInterpolatedV( var1 ); } @@ -95,5 +97,4 @@ public class MissingIcon implements IIcon { return this.getMissing().getIconName(); } - } diff --git a/src/main/java/appeng/client/texture/OffsetIcon.java b/src/main/java/appeng/client/texture/OffsetIcon.java index 936bb2c40..44487ddbb 100644 --- a/src/main/java/appeng/client/texture/OffsetIcon.java +++ b/src/main/java/appeng/client/texture/OffsetIcon.java @@ -18,11 +18,13 @@ package appeng.client.texture; + import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + public class OffsetIcon implements IIcon { @@ -31,75 +33,17 @@ public class OffsetIcon implements IIcon private final IIcon p; - public OffsetIcon(IIcon o, float x, float y) { + public OffsetIcon( IIcon o, float x, float y ) + { - if ( o == null ) - throw new RuntimeException("Cannot create a wrapper icon with a null icon."); + if( o == null ) + throw new RuntimeException( "Cannot create a wrapper icon with a null icon." ); this.p = o; this.offsetX = x; this.offsetY = y; } - @Override - @SideOnly(Side.CLIENT) - public float getMinU() - { - return this.u( 0 - this.offsetX ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMaxU() - { - return this.u( 16 - this.offsetX ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getInterpolatedU(double d0) - { - return this.u( d0 - this.offsetX ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMinV() - { - return this.v( 0 - this.offsetY ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMaxV() - { - return this.v( 16 - this.offsetY ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getInterpolatedV(double d0) - { - return this.v( d0 - this.offsetY ); - } - - private float v(double d) - { - return this.p.getInterpolatedV( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } - - private float u(double d) - { - return this.p.getInterpolatedU( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } - - @Override - @SideOnly(Side.CLIENT) - public String getIconName() - { - return this.p.getIconName(); - } - @Override public int getIconWidth() { @@ -112,4 +56,62 @@ public class OffsetIcon implements IIcon return this.p.getIconHeight(); } + @Override + @SideOnly( Side.CLIENT ) + public float getMinU() + { + return this.u( 0 - this.offsetX ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMaxU() + { + return this.u( 16 - this.offsetX ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getInterpolatedU( double d0 ) + { + return this.u( d0 - this.offsetX ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMinV() + { + return this.v( 0 - this.offsetY ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMaxV() + { + return this.v( 16 - this.offsetY ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getInterpolatedV( double d0 ) + { + return this.v( d0 - this.offsetY ); + } + + @Override + @SideOnly( Side.CLIENT ) + public String getIconName() + { + return this.p.getIconName(); + } + + private float v( double d ) + { + return this.p.getInterpolatedV( Math.min( 16.0, Math.max( 0.0, d ) ) ); + } + + private float u( double d ) + { + return this.p.getInterpolatedU( Math.min( 16.0, Math.max( 0.0, d ) ) ); + } } diff --git a/src/main/java/appeng/client/texture/TaughtIcon.java b/src/main/java/appeng/client/texture/TaughtIcon.java index 95e6acfe4..58eb34455 100644 --- a/src/main/java/appeng/client/texture/TaughtIcon.java +++ b/src/main/java/appeng/client/texture/TaughtIcon.java @@ -18,11 +18,13 @@ package appeng.client.texture; + import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; + public class TaughtIcon implements IIcon { @@ -30,82 +32,16 @@ public class TaughtIcon implements IIcon private final IIcon p; - public TaughtIcon(IIcon o, float tightness) { + public TaughtIcon( IIcon o, float tightness ) + { - if ( o == null ) - throw new RuntimeException("Cannot create a wrapper icon with a null icon."); + if( o == null ) + throw new RuntimeException( "Cannot create a wrapper icon with a null icon." ); this.p = o; this.tightness = tightness * 0.4f; } - @Override - @SideOnly(Side.CLIENT) - public float getMinU() - { - return this.u( 0 ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMaxU() - { - return this.u( 16 ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getInterpolatedU(double d0) - { - return this.u( d0 ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMinV() - { - return this.v( 0 ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getMaxV() - { - return this.v( 16 ); - } - - @Override - @SideOnly(Side.CLIENT) - public float getInterpolatedV(double d0) - { - return this.v( d0 ); - } - - private float v(double d) - { - if ( d < 8 ) - d -= this.tightness; - if ( d > 8 ) - d += this.tightness; - return this.p.getInterpolatedV( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } - - private float u(double d) - { - if ( d < 8 ) - d -= this.tightness; - if ( d > 8 ) - d += this.tightness; - return this.p.getInterpolatedU( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } - - @Override - @SideOnly(Side.CLIENT) - public String getIconName() - { - return this.p.getIconName(); - } - @Override public int getIconWidth() { @@ -118,4 +54,70 @@ public class TaughtIcon implements IIcon return this.p.getIconHeight(); } + @Override + @SideOnly( Side.CLIENT ) + public float getMinU() + { + return this.u( 0 ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMaxU() + { + return this.u( 16 ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getInterpolatedU( double d0 ) + { + return this.u( d0 ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMinV() + { + return this.v( 0 ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getMaxV() + { + return this.v( 16 ); + } + + @Override + @SideOnly( Side.CLIENT ) + public float getInterpolatedV( double d0 ) + { + return this.v( d0 ); + } + + @Override + @SideOnly( Side.CLIENT ) + public String getIconName() + { + return this.p.getIconName(); + } + + private float v( double d ) + { + if( d < 8 ) + d -= this.tightness; + if( d > 8 ) + d += this.tightness; + return this.p.getInterpolatedV( Math.min( 16.0, Math.max( 0.0, d ) ) ); + } + + private float u( double d ) + { + if( d < 8 ) + d -= this.tightness; + if( d > 8 ) + d += this.tightness; + return this.p.getInterpolatedU( Math.min( 16.0, Math.max( 0.0, d ) ) ); + } } diff --git a/src/main/java/appeng/client/texture/TmpFlippableIcon.java b/src/main/java/appeng/client/texture/TmpFlippableIcon.java index c662771f6..0b4725651 100644 --- a/src/main/java/appeng/client/texture/TmpFlippableIcon.java +++ b/src/main/java/appeng/client/texture/TmpFlippableIcon.java @@ -18,38 +18,40 @@ package appeng.client.texture; + import net.minecraft.init.Blocks; import net.minecraft.util.IIcon; + public class TmpFlippableIcon extends FlippableIcon { private static final IIcon NULL_ICON = new MissingIcon( Blocks.diamond_block ); - public TmpFlippableIcon() { + public TmpFlippableIcon() + { super( NULL_ICON ); } - public void setOriginal(IIcon i) + public void setOriginal( IIcon i ) { this.setFlip( false, false ); - while (i instanceof FlippableIcon) + while( i instanceof FlippableIcon ) { FlippableIcon fi = (FlippableIcon) i; - if ( fi.flip_u ) + if( fi.flip_u ) this.flip_u = !this.flip_u; - if ( fi.flip_v ) + if( fi.flip_v ) this.flip_v = !this.flip_v; i = fi.getOriginal(); } - if ( i == null ) + if( i == null ) this.original = NULL_ICON; else this.original = i; } - } diff --git a/src/main/java/appeng/container/AEBaseContainer.java b/src/main/java/appeng/container/AEBaseContainer.java index 47a3f411f..7ed6e0e57 100644 --- a/src/main/java/appeng/container/AEBaseContainer.java +++ b/src/main/java/appeng/container/AEBaseContainer.java @@ -18,6 +18,7 @@ package appeng.container; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -80,51 +81,112 @@ import appeng.util.Platform; import appeng.util.inv.AdaptorPlayerHand; import appeng.util.item.AEItemStack; + public abstract class AEBaseContainer extends Container { protected final InventoryPlayer invPlayer; + final protected BaseActionSource mySrc; + protected final HashSet locked = new HashSet(); final TileEntity tileEntity; final IPart part; final IGuiItemObject obj; - - final protected BaseActionSource mySrc; - public boolean isContainerValid = true; - - boolean sentCustomName; - public String customName; - - int ticksSinceCheck = 900; - - IAEItemStack clientRequestedTargetItem = null; final List dataChunks = new LinkedList(); + final HashMap syncData = new HashMap(); + public boolean isContainerValid = true; + public String customName; + public ContainerOpenContext openContext; + protected IMEInventoryHandler cellInv; + protected IEnergySource powerSrc; + boolean sentCustomName; + int ticksSinceCheck = 900; + IAEItemStack clientRequestedTargetItem = null; - public void postPartial(PacketPartialItem packetPartialItem) + public AEBaseContainer( InventoryPlayer ip, TileEntity myTile, IPart myPart ) + { + this( ip, myTile, myPart, null ); + } + + public AEBaseContainer( InventoryPlayer ip, TileEntity myTile, IPart myPart, IGuiItemObject gio ) + { + this.invPlayer = ip; + this.tileEntity = myTile; + this.part = myPart; + this.obj = gio; + this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); + this.prepareSync(); + } + + protected IActionHost getActionHost() + { + if( this.obj instanceof IActionHost ) + return (IActionHost) this.obj; + + if( this.tileEntity instanceof IActionHost ) + return (IActionHost) this.tileEntity; + + if( this.part instanceof IActionHost ) + return (IActionHost) this.part; + + return null; + } + + private void prepareSync() + { + for( Field f : this.getClass().getFields() ) + { + if( f.isAnnotationPresent( GuiSync.class ) ) + { + GuiSync annotation = f.getAnnotation( GuiSync.class ); + if( this.syncData.containsKey( annotation.value() ) ) + AELog.warning( "Channel already in use: " + annotation.value() + " for " + f.getName() ); + else + this.syncData.put( annotation.value(), new SyncData( this, f, annotation ) ); + } + } + } + + public AEBaseContainer( InventoryPlayer ip, Object anchor ) + { + this.invPlayer = ip; + this.tileEntity = anchor instanceof TileEntity ? (TileEntity) anchor : null; + this.part = anchor instanceof IPart ? (IPart) anchor : null; + this.obj = anchor instanceof IGuiItemObject ? (IGuiItemObject) anchor : null; + + if( this.tileEntity == null && this.part == null && this.obj == null ) + throw new RuntimeException( "Must have a valid anchor" ); + + this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); + + this.prepareSync(); + } + + public void postPartial( PacketPartialItem packetPartialItem ) { this.dataChunks.add( packetPartialItem ); - if ( packetPartialItem.getPageCount() == this.dataChunks.size() ) + if( packetPartialItem.getPageCount() == this.dataChunks.size() ) this.parsePartials(); } private void parsePartials() { int total = 0; - for (PacketPartialItem ppi : this.dataChunks) + for( PacketPartialItem ppi : this.dataChunks ) total += ppi.getSize(); byte[] buffer = new byte[total]; int cursor = 0; - for (PacketPartialItem ppi : this.dataChunks) + for( PacketPartialItem ppi : this.dataChunks ) cursor = ppi.write( buffer, cursor ); try { NBTTagCompound data = CompressedStreamTools.readCompressed( new ByteArrayInputStream( buffer ) ); - if ( data != null ) + if( data != null ) this.setTargetStack( AEApi.instance().storage().createItemStack( ItemStack.loadItemStackFromNBT( data ) ) ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } @@ -132,21 +194,26 @@ public abstract class AEBaseContainer extends Container this.dataChunks.clear(); } - public void setTargetStack(IAEItemStack stack) + public IAEItemStack getTargetStack() + { + return this.clientRequestedTargetItem; + } + + public void setTargetStack( IAEItemStack stack ) { // client doesn't need to re-send, makes for lower overhead rapid packets. - if ( Platform.isClient() ) + if( Platform.isClient() ) { ItemStack a = stack == null ? null : stack.getItemStack(); ItemStack b = this.clientRequestedTargetItem == null ? null : this.clientRequestedTargetItem.getItemStack(); - if ( Platform.isSameItemPrecise( a, b ) ) + if( Platform.isSameItemPrecise( a, b ) ) return; ByteArrayOutputStream stream = new ByteArrayOutputStream(); NBTTagCompound item = new NBTTagCompound(); - if ( stack != null ) + if( stack != null ) stack.writeToNBT( item ); try @@ -159,7 +226,7 @@ public abstract class AEBaseContainer extends Container byte[] data = stream.toByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream( data, 0, stream.size() ); - while (bis.available() > 0) + while( bis.available() > 0 ) { int nextBLock = bis.available() > maxChunkSize ? maxChunkSize : bis.available(); byte[] nextSegment = new byte[nextBLock]; @@ -170,14 +237,14 @@ public abstract class AEBaseContainer extends Container stream.close(); int page = 0; - for (byte[] packet : miniPackets) + for( byte[] packet : miniPackets ) { PacketPartialItem ppi = new PacketPartialItem( page, miniPackets.size(), packet ); page++; NetworkHandler.instance.sendToServer( ppi ); } } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); return; @@ -187,50 +254,45 @@ public abstract class AEBaseContainer extends Container this.clientRequestedTargetItem = stack == null ? null : stack.copy(); } - public IAEItemStack getTargetStack() - { - return this.clientRequestedTargetItem; - } - public BaseActionSource getSource() { return this.mySrc; } - public void verifyPermissions(SecurityPermissions security, boolean requirePower) + public void verifyPermissions( SecurityPermissions security, boolean requirePower ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; this.ticksSinceCheck++; - if ( this.ticksSinceCheck < 20 ) + if( this.ticksSinceCheck < 20 ) return; this.ticksSinceCheck = 0; this.isContainerValid = this.isContainerValid && this.hasAccess( security, requirePower ); } - protected boolean hasAccess(SecurityPermissions perm, boolean requirePower) + protected boolean hasAccess( SecurityPermissions perm, boolean requirePower ) { IActionHost host = this.getActionHost(); - if ( host != null ) + if( host != null ) { IGridNode gn = host.getActionableNode(); - if ( gn != null ) + if( gn != null ) { IGrid g = gn.getGrid(); - if ( g != null ) + if( g != null ) { - if ( requirePower ) + if( requirePower ) { IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if ( !eg.isNetworkPowered() ) + if( !eg.isNetworkPowered() ) return false; } ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if ( sg.hasPermission( this.invPlayer.player, perm ) ) + if( sg.hasPermission( this.invPlayer.player, perm ) ) return true; } } @@ -239,75 +301,22 @@ public abstract class AEBaseContainer extends Container return false; } - public ContainerOpenContext openContext; - - protected IMEInventoryHandler cellInv; - protected final HashSet locked = new HashSet(); - protected IEnergySource powerSrc; - - public void lockPlayerInventorySlot(int idx) + public void lockPlayerInventorySlot( int idx ) { this.locked.add( idx ); } public Object getTarget() { - if ( this.tileEntity != null ) + if( this.tileEntity != null ) return this.tileEntity; - if ( this.part != null ) + if( this.part != null ) return this.part; - if ( this.obj != null ) + if( this.obj != null ) return this.obj; return null; } - public AEBaseContainer(InventoryPlayer ip, TileEntity myTile, IPart myPart) { - this( ip, myTile, myPart, null ); - } - - public AEBaseContainer(InventoryPlayer ip, TileEntity myTile, IPart myPart, IGuiItemObject gio) { - this.invPlayer = ip; - this.tileEntity = myTile; - this.part = myPart; - this.obj = gio; - this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); - this.prepareSync(); - } - - public AEBaseContainer(InventoryPlayer ip, Object anchor) { - this.invPlayer = ip; - this.tileEntity = anchor instanceof TileEntity ? (TileEntity) anchor : null; - this.part = anchor instanceof IPart ? (IPart) anchor : null; - this.obj = anchor instanceof IGuiItemObject ? (IGuiItemObject) anchor : null; - - if ( this.tileEntity == null && this.part == null && this.obj == null ) - throw new RuntimeException( "Must have a valid anchor" ); - - this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); - - this.prepareSync(); - } - - protected IActionHost getActionHost() - { - if ( this.obj instanceof IActionHost ) - return (IActionHost) this.obj; - - if ( this.tileEntity instanceof IActionHost ) - return (IActionHost) this.tileEntity; - - if ( this.part instanceof IActionHost ) - return (IActionHost) this.part; - - return null; - } - - @Override - public boolean canDragIntoSlot(Slot s) - { - return ((AppEngSlot) s).isDraggable; - } - public InventoryPlayer getPlayerInv() { return this.invPlayer; @@ -318,10 +327,51 @@ public abstract class AEBaseContainer extends Container return this.tileEntity; } - @Override - protected Slot addSlotToContainer(Slot newSlot) + final public void updateFullProgressBar( int idx, long value ) { - if ( newSlot instanceof AppEngSlot ) + if( this.syncData.containsKey( idx ) ) + { + this.syncData.get( idx ).update( value ); + return; + } + + this.updateProgressBar( idx, (int) value ); + } + + public void stringSync( int idx, String value ) + { + if( this.syncData.containsKey( idx ) ) + { + this.syncData.get( idx ).update( value ); + } + } + + protected void bindPlayerInventory( InventoryPlayer inventoryPlayer, int offset_x, int offset_y ) + { + for( int i = 0; i < 9; i++ ) + { + if( this.locked.contains( i ) ) + this.addSlotToContainer( new SlotDisabled( inventoryPlayer, i, 8 + i * 18 + offset_x, 58 + offset_y ) ); + else + this.addSlotToContainer( new SlotPlayerHotBar( inventoryPlayer, i, 8 + i * 18 + offset_x, 58 + offset_y ) ); + } + + for( int i = 0; i < 3; i++ ) + { + for( int j = 0; j < 9; j++ ) + { + if( this.locked.contains( j + i * 9 + 9 ) ) + this.addSlotToContainer( new SlotDisabled( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offset_x, offset_y + i * 18 ) ); + else + this.addSlotToContainer( new SlotPlayerInv( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offset_x, offset_y + i * 18 ) ); + } + } + } + + @Override + protected Slot addSlotToContainer( Slot newSlot ) + { + if( newSlot instanceof AppEngSlot ) { AppEngSlot s = (AppEngSlot) newSlot; s.myContainer = this; @@ -332,34 +382,41 @@ public abstract class AEBaseContainer extends Container } @Override - public boolean canInteractWith(EntityPlayer entityplayer) + public void detectAndSendChanges() { - if ( this.isContainerValid ) + this.sendCustomName(); + + if( Platform.isServer() ) { - if ( this.tileEntity instanceof IInventory ) - return ((IInventory) this.tileEntity).isUseableByPlayer( entityplayer ); - return true; + for( Object crafter : this.crafters ) + { + ICrafting icrafting = (ICrafting) crafter; + + for( SyncData sd : this.syncData.values() ) + sd.tick( icrafting ); + } } - return false; + + super.detectAndSendChanges(); } @Override - public ItemStack transferStackInSlot(EntityPlayer p, int idx) + public ItemStack transferStackInSlot( EntityPlayer p, int idx ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return null; boolean hasMETiles = false; - for (Object is : this.inventorySlots) + for( Object is : this.inventorySlots ) { - if ( is instanceof InternalSlotME ) + if( is instanceof InternalSlotME ) { hasMETiles = true; break; } } - if ( hasMETiles && Platform.isClient() ) + if( hasMETiles && Platform.isClient() ) { return null; } @@ -367,13 +424,13 @@ public abstract class AEBaseContainer extends Container ItemStack tis = null; AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots! - if ( clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible ) + if( clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible ) return null; - if ( clickSlot != null && clickSlot.getHasStack() ) + if( clickSlot != null && clickSlot.getHasStack() ) { tis = clickSlot.getStack(); - if ( tis == null ) + if( tis == null ) return null; List selectedSlots = new ArrayList(); @@ -381,18 +438,18 @@ public abstract class AEBaseContainer extends Container /** * Gather a list of valid destinations. */ - if ( clickSlot.isPlayerSide() ) + if( clickSlot.isPlayerSide() ) { tis = this.shiftStoreItem( tis ); // target slots in the container... - for (Object inventorySlot : this.inventorySlots) + for( Object inventorySlot : this.inventorySlots ) { AppEngSlot cs = (AppEngSlot) inventorySlot; - if ( !(cs.isPlayerSide()) && !(cs instanceof SlotFake) && !(cs instanceof SlotCraftingMatrix) ) + if( !( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) { - if ( cs.isItemValid( tis ) ) + if( cs.isItemValid( tis ) ) { selectedSlots.add( cs ); } @@ -402,13 +459,13 @@ public abstract class AEBaseContainer extends Container else { // target slots in the container... - for (Object inventorySlot : this.inventorySlots) + for( Object inventorySlot : this.inventorySlots ) { AppEngSlot cs = (AppEngSlot) inventorySlot; - if ( (cs.isPlayerSide()) && !(cs instanceof SlotFake) && !(cs instanceof SlotCraftingMatrix) ) + if( ( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) { - if ( cs.isItemValid( tis ) ) + if( cs.isItemValid( tis ) ) { selectedSlots.add( cs ); } @@ -419,23 +476,23 @@ public abstract class AEBaseContainer extends Container /** * Handle Fake Slot Shift clicking. */ - if ( selectedSlots.isEmpty() && clickSlot.isPlayerSide() ) + if( selectedSlots.isEmpty() && clickSlot.isPlayerSide() ) { - if ( tis != null ) + if( tis != null ) { // target slots in the container... - for (Object inventorySlot : this.inventorySlots) + for( Object inventorySlot : this.inventorySlots ) { AppEngSlot cs = (AppEngSlot) inventorySlot; ItemStack destination = cs.getStack(); - if ( !(cs.isPlayerSide()) && cs instanceof SlotFake ) + if( !( cs.isPlayerSide() ) && cs instanceof SlotFake ) { - if ( Platform.isSameItemPrecise( destination, tis ) ) + if( Platform.isSameItemPrecise( destination, tis ) ) { return null; } - else if ( destination == null ) + else if( destination == null ) { cs.putStack( tis.copy() ); cs.onSlotChanged(); @@ -447,29 +504,29 @@ public abstract class AEBaseContainer extends Container } } - if ( tis != null ) + if( tis != null ) { // find partials.. - for (Slot d : selectedSlots) + for( Slot d : selectedSlots ) { - if ( d instanceof SlotDisabled || d instanceof SlotME ) + if( d instanceof SlotDisabled || d instanceof SlotME ) continue; - if ( d.isItemValid( tis ) ) + if( d.isItemValid( tis ) ) { - if ( d.getHasStack() ) + if( d.getHasStack() ) { ItemStack t = d.getStack(); - if ( Platform.isSameItemPrecise( tis, t ) ) // t.isItemEqual(tis)) + if( Platform.isSameItemPrecise( tis, t ) ) // t.isItemEqual(tis)) { int maxSize = t.getMaxStackSize(); - if ( maxSize > d.getSlotStackLimit() ) + if( maxSize > d.getSlotStackLimit() ) maxSize = d.getSlotStackLimit(); int placeAble = maxSize - t.stackSize; - if ( tis.stackSize < placeAble ) + if( tis.stackSize < placeAble ) { placeAble = tis.stackSize; } @@ -477,7 +534,7 @@ public abstract class AEBaseContainer extends Container t.stackSize += placeAble; tis.stackSize -= placeAble; - if ( tis.stackSize <= 0 ) + if( tis.stackSize <= 0 ) { clickSlot.putStack( null ); d.onSlotChanged(); @@ -496,26 +553,26 @@ public abstract class AEBaseContainer extends Container } // any match.. - for (Slot d : selectedSlots) + for( Slot d : selectedSlots ) { - if ( d instanceof SlotDisabled || d instanceof SlotME ) + if( d instanceof SlotDisabled || d instanceof SlotME ) continue; - if ( d.isItemValid( tis ) ) + if( d.isItemValid( tis ) ) { - if ( d.getHasStack() ) + if( d.getHasStack() ) { ItemStack t = d.getStack(); - if ( Platform.isSameItemPrecise( t, tis ) ) + if( Platform.isSameItemPrecise( t, tis ) ) { int maxSize = t.getMaxStackSize(); - if ( d.getSlotStackLimit() < maxSize ) + if( d.getSlotStackLimit() < maxSize ) maxSize = d.getSlotStackLimit(); int placeAble = maxSize - t.stackSize; - if ( tis.stackSize < placeAble ) + if( tis.stackSize < placeAble ) { placeAble = tis.stackSize; } @@ -523,7 +580,7 @@ public abstract class AEBaseContainer extends Container t.stackSize += placeAble; tis.stackSize -= placeAble; - if ( tis.stackSize <= 0 ) + if( tis.stackSize <= 0 ) { clickSlot.putStack( null ); d.onSlotChanged(); @@ -543,17 +600,17 @@ public abstract class AEBaseContainer extends Container else { int maxSize = tis.getMaxStackSize(); - if ( maxSize > d.getSlotStackLimit() ) + if( maxSize > d.getSlotStackLimit() ) maxSize = d.getSlotStackLimit(); ItemStack tmp = tis.copy(); - if ( tmp.stackSize > maxSize ) + if( tmp.stackSize > maxSize ) tmp.stackSize = maxSize; tis.stackSize -= tmp.stackSize; d.putStack( tmp ); - if ( tis.stackSize <= 0 ) + if( tis.stackSize <= 0 ) { clickSlot.putStack( null ); d.onSlotChanged(); @@ -580,238 +637,120 @@ public abstract class AEBaseContainer extends Container return null; } - private void updateSlot(Slot clickSlot) - { - // ??? - this.detectAndSendChanges(); - } - - final HashMap syncData = new HashMap(); - @Override - public void detectAndSendChanges() + final public void updateProgressBar( int idx, int value ) { - this.sendCustomName(); - - if ( Platform.isServer() ) - { - for (Object crafter : this.crafters) - { - ICrafting icrafting = (ICrafting) crafter; - - for (SyncData sd : this.syncData.values()) - sd.tick( icrafting ); - } - } - - super.detectAndSendChanges(); - } - - @Override - final public void updateProgressBar(int idx, int value) - { - if ( this.syncData.containsKey( idx ) ) + if( this.syncData.containsKey( idx ) ) { this.syncData.get( idx ).update( (long) value ); } } - final public void updateFullProgressBar(int idx, long value) + @Override + public boolean canInteractWith( EntityPlayer entityplayer ) { - if ( this.syncData.containsKey( idx ) ) + if( this.isContainerValid ) { - this.syncData.get( idx ).update( value ); - return; + if( this.tileEntity instanceof IInventory ) + return ( (IInventory) this.tileEntity ).isUseableByPlayer( entityplayer ); + return true; } - - this.updateProgressBar( idx, (int) value ); + return false; } - public void stringSync(int idx, String value) + @Override + public boolean canDragIntoSlot( Slot s ) { - if ( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( value ); - } + return ( (AppEngSlot) s ).isDraggable; } - private void prepareSync() + public void doAction( EntityPlayerMP player, InventoryAction action, int slot, long id ) { - for (Field f : this.getClass().getFields()) - { - if ( f.isAnnotationPresent( GuiSync.class ) ) - { - GuiSync annotation = f.getAnnotation( GuiSync.class ); - if ( this.syncData.containsKey( annotation.value() ) ) - AELog.warning( "Channel already in use: " + annotation.value() + " for " + f.getName() ); - else - this.syncData.put( annotation.value(), new SyncData( this, f, annotation ) ); - } - } - } - - protected void sendCustomName() - { - if ( !this.sentCustomName ) - { - this.sentCustomName = true; - if ( Platform.isServer() ) - { - ICustomNameObject name = null; - - if ( this.part instanceof ICustomNameObject ) - name = (ICustomNameObject) this.part; - - if ( this.tileEntity instanceof ICustomNameObject ) - name = (ICustomNameObject) this.tileEntity; - - if ( this.obj instanceof ICustomNameObject ) - name = (ICustomNameObject) this.obj; - - if ( this instanceof ICustomNameObject ) - name = (ICustomNameObject) this; - - if ( name != null ) - { - if ( name.hasCustomName() ) - this.customName = name.getCustomName(); - - if ( this.customName != null ) - { - try - { - NetworkHandler.instance.sendTo( new PacketValueConfig( "CustomName", this.customName ), (EntityPlayerMP) this.invPlayer.player ); - } - catch (IOException e) - { - AELog.error( e ); - } - } - } - } - } - } - - protected void bindPlayerInventory(InventoryPlayer inventoryPlayer, int offset_x, int offset_y) - { - for (int i = 0; i < 9; i++) - { - if ( this.locked.contains( i ) ) - this.addSlotToContainer( new SlotDisabled( inventoryPlayer, i, 8 + i * 18 + offset_x, 58 + offset_y ) ); - else - this.addSlotToContainer( new SlotPlayerHotBar( inventoryPlayer, i, 8 + i * 18 + offset_x, 58 + offset_y ) ); - } - - for (int i = 0; i < 3; i++) - { - for (int j = 0; j < 9; j++) - { - if ( this.locked.contains( j + i * 9 + 9 ) ) - this.addSlotToContainer( new SlotDisabled( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offset_x, offset_y + i * 18 ) ); - else - this.addSlotToContainer( new SlotPlayerInv( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offset_x, offset_y + i * 18 ) ); - } - } - } - - public ItemStack shiftStoreItem(ItemStack input) - { - if ( this.powerSrc == null || this.cellInv == null ) - return input; - IAEItemStack ais = Platform.poweredInsert( this.powerSrc, this.cellInv, AEApi.instance().storage().createItemStack( input ), this.mySrc ); - if ( ais == null ) - return null; - return ais.getItemStack(); - } - - public void doAction(EntityPlayerMP player, InventoryAction action, int slot, long id) - { - if ( slot >= 0 && slot < this.inventorySlots.size() ) + if( slot >= 0 && slot < this.inventorySlots.size() ) { Slot s = this.getSlot( slot ); - if ( s instanceof SlotCraftingTerm ) + if( s instanceof SlotCraftingTerm ) { - switch (action) + switch( action ) { - case CRAFT_SHIFT: - case CRAFT_ITEM: - case CRAFT_STACK: - ((SlotCraftingTerm) s).doClick( action, player ); - this.updateHeld( player ); - default: + case CRAFT_SHIFT: + case CRAFT_ITEM: + case CRAFT_STACK: + ( (SlotCraftingTerm) s ).doClick( action, player ); + this.updateHeld( player ); + default: } } - if ( s instanceof SlotFake ) + if( s instanceof SlotFake ) { ItemStack hand = player.inventory.getItemStack(); - switch (action) + switch( action ) { - case PICKUP_OR_SET_DOWN: + case PICKUP_OR_SET_DOWN: - if ( hand == null ) - s.putStack( null ); - else - s.putStack( hand.copy() ); - - break; - case PLACE_SINGLE: - - if ( hand != null ) - { - ItemStack is = hand.copy(); - is.stackSize = 1; - s.putStack( is ); - } - - break; - case SPLIT_OR_PLACE_SINGLE: - - ItemStack is = s.getStack(); - if ( is != null ) - { - if ( hand == null ) - is.stackSize--; - else if ( hand.isItemEqual( is ) ) - is.stackSize = Math.min( is.getMaxStackSize(), is.stackSize + 1 ); + if( hand == null ) + s.putStack( null ); else + s.putStack( hand.copy() ); + + break; + case PLACE_SINGLE: + + if( hand != null ) + { + ItemStack is = hand.copy(); + is.stackSize = 1; + s.putStack( is ); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + + ItemStack is = s.getStack(); + if( is != null ) + { + if( hand == null ) + is.stackSize--; + else if( hand.isItemEqual( is ) ) + is.stackSize = Math.min( is.getMaxStackSize(), is.stackSize + 1 ); + else + { + is = hand.copy(); + is.stackSize = 1; + } + + s.putStack( is ); + } + else if( hand != null ) { is = hand.copy(); is.stackSize = 1; + s.putStack( is ); } - s.putStack( is ); - } - else if ( hand != null ) - { - is = hand.copy(); - is.stackSize = 1; - s.putStack( is ); - } - - break; - case CREATIVE_DUPLICATE: - case MOVE_REGION: - case SHIFT_CLICK: - default: - break; - + break; + case CREATIVE_DUPLICATE: + case MOVE_REGION: + case SHIFT_CLICK: + default: + break; } } - if ( action == InventoryAction.MOVE_REGION ) + if( action == InventoryAction.MOVE_REGION ) { List from = new LinkedList(); - for (Object j : this.inventorySlots) + for( Object j : this.inventorySlots ) { - if ( j instanceof Slot && j.getClass() == s.getClass() ) + if( j instanceof Slot && j.getClass() == s.getClass() ) from.add( (Slot) j ); } - for (Slot fr : from) + for( Slot fr : from ) this.transferStackInSlot( player, fr.slotNumber ); } @@ -821,185 +760,13 @@ public abstract class AEBaseContainer extends Container // get target item. IAEItemStack slotItem = this.clientRequestedTargetItem; - switch (action) + switch( action ) { - case SHIFT_CLICK: - if ( this.powerSrc == null || this.cellInv == null ) - return; + case SHIFT_CLICK: + if( this.powerSrc == null || this.cellInv == null ) + return; - if ( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - ItemStack myItem = ais.getItemStack(); - - ais.setStackSize( myItem.getMaxStackSize() ); - - InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - myItem.stackSize = (int) ais.getStackSize(); - myItem = adp.simulateAdd( myItem ); - - if ( myItem != null ) - ais.setStackSize( ais.getStackSize() - myItem.stackSize ); - - ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); - if ( ais != null ) - adp.addItems( ais.getItemStack() ); - } - break; - case ROLL_DOWN: - if ( this.powerSrc == null || this.cellInv == null ) - return; - - int releaseQty = 1; - ItemStack isg = player.inventory.getItemStack(); - - if ( isg != null && releaseQty > 0 ) - { - IAEItemStack ais = AEApi.instance().storage().createItemStack( isg ); - ais.setStackSize( 1 ); - IAEItemStack extracted = ais.copy(); - - ais = Platform.poweredInsert( this.powerSrc, this.cellInv, ais, this.mySrc ); - if ( ais == null ) - { - InventoryAdaptor ia = new AdaptorPlayerHand( player ); - - ItemStack fail = ia.removeItems( 1, extracted.getItemStack(), null ); - if ( fail == null ) - this.cellInv.extractItems( extracted, Actionable.MODULATE, this.mySrc ); - - this.updateHeld( player ); - } - } - - break; - case ROLL_UP: - case PICKUP_SINGLE: - if ( this.powerSrc == null || this.cellInv == null ) - return; - - if ( slotItem != null ) - { - int liftQty = 1; - ItemStack item = player.inventory.getItemStack(); - - if ( item != null ) - { - if ( item.stackSize >= item.getMaxStackSize() ) - liftQty = 0; - if ( !Platform.isSameItemPrecise( slotItem.getItemStack(), item ) ) - liftQty = 0; - } - - if ( liftQty > 0 ) - { - IAEItemStack ais = slotItem.copy(); - ais.setStackSize( 1 ); - ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); - if ( ais != null ) - { - InventoryAdaptor ia = new AdaptorPlayerHand( player ); - - ItemStack fail = ia.addItems( ais.getItemStack() ); - if ( fail != null ) - this.cellInv.injectItems( ais, Actionable.MODULATE, this.mySrc ); - - this.updateHeld( player ); - } - } - } - break; - case PICKUP_OR_SET_DOWN: - if ( this.powerSrc == null || this.cellInv == null ) - return; - - if ( player.inventory.getItemStack() == null ) - { - if ( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - ais.setStackSize( ais.getItemStack().getMaxStackSize() ); - ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); - if ( ais != null ) - player.inventory.setItemStack( ais.getItemStack() ); - else - player.inventory.setItemStack( null ); - this.updateHeld( player ); - } - } - else - { - IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); - ais = Platform.poweredInsert( this.powerSrc, this.cellInv, ais, this.mySrc ); - if ( ais != null ) - player.inventory.setItemStack( ais.getItemStack() ); - else - player.inventory.setItemStack( null ); - this.updateHeld( player ); - } - - break; - case SPLIT_OR_PLACE_SINGLE: - if ( this.powerSrc == null || this.cellInv == null ) - return; - - if ( player.inventory.getItemStack() == null ) - { - if ( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - long maxSize = ais.getItemStack().getMaxStackSize(); - ais.setStackSize( maxSize ); - ais = this.cellInv.extractItems( ais, Actionable.SIMULATE, this.mySrc ); - - if ( ais != null ) - { - long stackSize = Math.min( maxSize, ais.getStackSize() ); - ais.setStackSize( (stackSize + 1) >> 1 ); - ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); - } - - if ( ais != null ) - player.inventory.setItemStack( ais.getItemStack() ); - else - player.inventory.setItemStack( null ); - this.updateHeld( player ); - } - } - else - { - IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); - ais.setStackSize( 1 ); - ais = Platform.poweredInsert( this.powerSrc, this.cellInv, ais, this.mySrc ); - if ( ais == null ) - { - ItemStack is = player.inventory.getItemStack(); - is.stackSize--; - if ( is.stackSize <= 0 ) - player.inventory.setItemStack( null ); - this.updateHeld( player ); - } - } - - break; - case CREATIVE_DUPLICATE: - if ( player.capabilities.isCreativeMode && slotItem != null ) - { - ItemStack is = slotItem.getItemStack(); - is.stackSize = is.getMaxStackSize(); - player.inventory.setItemStack( is ); - this.updateHeld( player ); - } - break; - case MOVE_REGION: - - if ( this.powerSrc == null || this.cellInv == null ) - return; - - if ( slotItem != null ) - { - int playerInv = 9 * 4; - for (int slotNum = 0; slotNum < playerInv; slotNum++) + if( slotItem != null ) { IAEItemStack ais = slotItem.copy(); ItemStack myItem = ais.getItemStack(); @@ -1010,78 +777,307 @@ public abstract class AEBaseContainer extends Container myItem.stackSize = (int) ais.getStackSize(); myItem = adp.simulateAdd( myItem ); - if ( myItem != null ) + if( myItem != null ) ais.setStackSize( ais.getStackSize() - myItem.stackSize ); ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); - if ( ais != null ) + if( ais != null ) adp.addItems( ais.getItemStack() ); - else - return; } - } + break; + case ROLL_DOWN: + if( this.powerSrc == null || this.cellInv == null ) + return; - break; - default: - break; + int releaseQty = 1; + ItemStack isg = player.inventory.getItemStack(); + + if( isg != null && releaseQty > 0 ) + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( isg ); + ais.setStackSize( 1 ); + IAEItemStack extracted = ais.copy(); + + ais = Platform.poweredInsert( this.powerSrc, this.cellInv, ais, this.mySrc ); + if( ais == null ) + { + InventoryAdaptor ia = new AdaptorPlayerHand( player ); + + ItemStack fail = ia.removeItems( 1, extracted.getItemStack(), null ); + if( fail == null ) + this.cellInv.extractItems( extracted, Actionable.MODULATE, this.mySrc ); + + this.updateHeld( player ); + } + } + + break; + case ROLL_UP: + case PICKUP_SINGLE: + if( this.powerSrc == null || this.cellInv == null ) + return; + + if( slotItem != null ) + { + int liftQty = 1; + ItemStack item = player.inventory.getItemStack(); + + if( item != null ) + { + if( item.stackSize >= item.getMaxStackSize() ) + liftQty = 0; + if( !Platform.isSameItemPrecise( slotItem.getItemStack(), item ) ) + liftQty = 0; + } + + if( liftQty > 0 ) + { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize( 1 ); + ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); + if( ais != null ) + { + InventoryAdaptor ia = new AdaptorPlayerHand( player ); + + ItemStack fail = ia.addItems( ais.getItemStack() ); + if( fail != null ) + this.cellInv.injectItems( ais, Actionable.MODULATE, this.mySrc ); + + this.updateHeld( player ); + } + } + } + break; + case PICKUP_OR_SET_DOWN: + if( this.powerSrc == null || this.cellInv == null ) + return; + + if( player.inventory.getItemStack() == null ) + { + if( slotItem != null ) + { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize( ais.getItemStack().getMaxStackSize() ); + ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); + if( ais != null ) + player.inventory.setItemStack( ais.getItemStack() ); + else + player.inventory.setItemStack( null ); + this.updateHeld( player ); + } + } + else + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); + ais = Platform.poweredInsert( this.powerSrc, this.cellInv, ais, this.mySrc ); + if( ais != null ) + player.inventory.setItemStack( ais.getItemStack() ); + else + player.inventory.setItemStack( null ); + this.updateHeld( player ); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + if( this.powerSrc == null || this.cellInv == null ) + return; + + if( player.inventory.getItemStack() == null ) + { + if( slotItem != null ) + { + IAEItemStack ais = slotItem.copy(); + long maxSize = ais.getItemStack().getMaxStackSize(); + ais.setStackSize( maxSize ); + ais = this.cellInv.extractItems( ais, Actionable.SIMULATE, this.mySrc ); + + if( ais != null ) + { + long stackSize = Math.min( maxSize, ais.getStackSize() ); + ais.setStackSize( ( stackSize + 1 ) >> 1 ); + ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); + } + + if( ais != null ) + player.inventory.setItemStack( ais.getItemStack() ); + else + player.inventory.setItemStack( null ); + this.updateHeld( player ); + } + } + else + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); + ais.setStackSize( 1 ); + ais = Platform.poweredInsert( this.powerSrc, this.cellInv, ais, this.mySrc ); + if( ais == null ) + { + ItemStack is = player.inventory.getItemStack(); + is.stackSize--; + if( is.stackSize <= 0 ) + player.inventory.setItemStack( null ); + this.updateHeld( player ); + } + } + + break; + case CREATIVE_DUPLICATE: + if( player.capabilities.isCreativeMode && slotItem != null ) + { + ItemStack is = slotItem.getItemStack(); + is.stackSize = is.getMaxStackSize(); + player.inventory.setItemStack( is ); + this.updateHeld( player ); + } + break; + case MOVE_REGION: + + if( this.powerSrc == null || this.cellInv == null ) + return; + + if( slotItem != null ) + { + int playerInv = 9 * 4; + for( int slotNum = 0; slotNum < playerInv; slotNum++ ) + { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize( myItem.getMaxStackSize() ); + + InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); + myItem.stackSize = (int) ais.getStackSize(); + myItem = adp.simulateAdd( myItem ); + + if( myItem != null ) + ais.setStackSize( ais.getStackSize() - myItem.stackSize ); + + ais = Platform.poweredExtraction( this.powerSrc, this.cellInv, ais, this.mySrc ); + if( ais != null ) + adp.addItems( ais.getItemStack() ); + else + return; + } + } + + break; + default: + break; } } - protected void updateHeld(EntityPlayerMP p) + protected void updateHeld( EntityPlayerMP p ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) { try { - NetworkHandler.instance.sendTo( new PacketInventoryAction( InventoryAction.UPDATE_HAND, 0, AEItemStack.create( p.inventory.getItemStack() ) ), - p ); + NetworkHandler.instance.sendTo( new PacketInventoryAction( InventoryAction.UPDATE_HAND, 0, AEItemStack.create( p.inventory.getItemStack() ) ), p ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } } } - public void swapSlotContents(int slotA, int slotB) + public ItemStack shiftStoreItem( ItemStack input ) + { + if( this.powerSrc == null || this.cellInv == null ) + return input; + IAEItemStack ais = Platform.poweredInsert( this.powerSrc, this.cellInv, AEApi.instance().storage().createItemStack( input ), this.mySrc ); + if( ais == null ) + return null; + return ais.getItemStack(); + } + + private void updateSlot( Slot clickSlot ) + { + // ??? + this.detectAndSendChanges(); + } + + protected void sendCustomName() + { + if( !this.sentCustomName ) + { + this.sentCustomName = true; + if( Platform.isServer() ) + { + ICustomNameObject name = null; + + if( this.part instanceof ICustomNameObject ) + name = (ICustomNameObject) this.part; + + if( this.tileEntity instanceof ICustomNameObject ) + name = (ICustomNameObject) this.tileEntity; + + if( this.obj instanceof ICustomNameObject ) + name = (ICustomNameObject) this.obj; + + if( this instanceof ICustomNameObject ) + name = (ICustomNameObject) this; + + if( name != null ) + { + if( name.hasCustomName() ) + this.customName = name.getCustomName(); + + if( this.customName != null ) + { + try + { + NetworkHandler.instance.sendTo( new PacketValueConfig( "CustomName", this.customName ), (EntityPlayerMP) this.invPlayer.player ); + } + catch( IOException e ) + { + AELog.error( e ); + } + } + } + } + } + } + + public void swapSlotContents( int slotA, int slotB ) { Slot a = this.getSlot( slotA ); Slot b = this.getSlot( slotB ); // NPE protection... - if ( a == null || b == null ) + if( a == null || b == null ) return; ItemStack isA = a.getStack(); ItemStack isB = b.getStack(); // something to do? - if ( isA == null && isB == null ) + if( isA == null && isB == null ) return; // can take? - if ( isA != null && !a.canTakeStack( this.invPlayer.player ) ) + if( isA != null && !a.canTakeStack( this.invPlayer.player ) ) return; - if ( isB != null && !b.canTakeStack( this.invPlayer.player ) ) + if( isB != null && !b.canTakeStack( this.invPlayer.player ) ) return; // swap valid? - if ( isB != null && !a.isItemValid( isB ) ) + if( isB != null && !a.isItemValid( isB ) ) return; - if ( isA != null && !b.isItemValid( isA ) ) + if( isA != null && !b.isItemValid( isA ) ) return; ItemStack testA = isB == null ? null : isB.copy(); ItemStack testB = isA == null ? null : isA.copy(); // can put some back? - if ( testA != null && testA.stackSize > a.getSlotStackLimit() ) + if( testA != null && testA.stackSize > a.getSlotStackLimit() ) { - if ( testB != null ) + if( testB != null ) return; int totalA = testA.stackSize; @@ -1091,9 +1087,9 @@ public abstract class AEBaseContainer extends Container testB.stackSize = totalA - testA.stackSize; } - if ( testB != null && testB.stackSize > b.getSlotStackLimit() ) + if( testB != null && testB.stackSize > b.getSlotStackLimit() ) { - if ( testA != null ) + if( testA != null ) return; int totalB = testB.stackSize; @@ -1107,19 +1103,18 @@ public abstract class AEBaseContainer extends Container b.putStack( testB ); } - public void onUpdate(String field, Object oldValue, Object newValue) + public void onUpdate( String field, Object oldValue, Object newValue ) { } - public void onSlotChange(Slot s) + public void onSlotChange( Slot s ) { } - public boolean isValidForSlot(Slot s, ItemStack i) + public boolean isValidForSlot( Slot s, ItemStack i ) { return true; } - } diff --git a/src/main/java/appeng/container/ContainerNull.java b/src/main/java/appeng/container/ContainerNull.java index 57f7db212..c1c8ee737 100644 --- a/src/main/java/appeng/container/ContainerNull.java +++ b/src/main/java/appeng/container/ContainerNull.java @@ -18,9 +18,11 @@ package appeng.container; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; + /* * Totally useless container that does nothing. */ @@ -28,9 +30,8 @@ public class ContainerNull extends Container { @Override - public boolean canInteractWith(EntityPlayer entityplayer) + public boolean canInteractWith( EntityPlayer entityplayer ) { return false; } - } diff --git a/src/main/java/appeng/container/ContainerOpenContext.java b/src/main/java/appeng/container/ContainerOpenContext.java index e7443156e..b3b2304e8 100644 --- a/src/main/java/appeng/container/ContainerOpenContext.java +++ b/src/main/java/appeng/container/ContainerOpenContext.java @@ -18,32 +18,34 @@ package appeng.container; + import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import appeng.api.parts.IPart; + public class ContainerOpenContext { + final public boolean isItem; public World w; public int x; public int y; public int z; public ForgeDirection side; - final public boolean isItem; - public ContainerOpenContext(Object myItem) { + public ContainerOpenContext( Object myItem ) + { boolean isWorld = myItem instanceof IPart || myItem instanceof TileEntity; this.isItem = !isWorld; } public TileEntity getTile() { - if ( this.isItem ) + if( this.isItem ) return null; return this.w.getTileEntity( this.x, this.y, this.z ); } - } diff --git a/src/main/java/appeng/container/guisync/GuiSync.java b/src/main/java/appeng/container/guisync/GuiSync.java index fd1024ba2..4a68fde01 100644 --- a/src/main/java/appeng/container/guisync/GuiSync.java +++ b/src/main/java/appeng/container/guisync/GuiSync.java @@ -18,12 +18,14 @@ package appeng.container.guisync; + import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -@Retention(RetentionPolicy.RUNTIME) -public @interface GuiSync { + +@Retention( RetentionPolicy.RUNTIME ) +public @interface GuiSync +{ int value(); - } diff --git a/src/main/java/appeng/container/guisync/SyncData.java b/src/main/java/appeng/container/guisync/SyncData.java index 5777e6e56..20e0707e1 100644 --- a/src/main/java/appeng/container/guisync/SyncData.java +++ b/src/main/java/appeng/container/guisync/SyncData.java @@ -18,6 +18,7 @@ package appeng.container.guisync; + import java.io.IOException; import java.lang.reflect.Field; import java.util.EnumSet; @@ -31,17 +32,17 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketProgressBar; import appeng.core.sync.packets.PacketValueConfig; + public class SyncData { - private Object clientVersion; - private final AEBaseContainer source; private final Field field; - private final int channel; + private Object clientVersion; - public SyncData(AEBaseContainer container, Field field, GuiSync annotation) { + public SyncData( AEBaseContainer container, Field field, GuiSync annotation ) + { this.clientVersion = null; this.source = container; this.field = field; @@ -53,129 +54,48 @@ public class SyncData return this.channel; } - public void tick(ICrafting c) + public void tick( ICrafting c ) { try { Object val = this.field.get( this.source ); - if ( val != null && this.clientVersion == null ) + if( val != null && this.clientVersion == null ) this.send( c, val ); - else if ( !val.equals( this.clientVersion ) ) + else if( !val.equals( this.clientVersion ) ) this.send( c, val ); } - catch (IllegalArgumentException e) + catch( IllegalArgumentException e ) { AELog.error( e ); } - catch (IllegalAccessException e) + catch( IllegalAccessException e ) { AELog.error( e ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } } - public void update(Object val) + private void send( ICrafting o, Object val ) throws IOException { - try + if( val instanceof String ) { - Object oldValue = this.field.get( this.source ); - if ( val instanceof String ) - this.updateString( oldValue, (String) val ); - else - this.updateValue( oldValue, (Long) val ); - } - catch (IllegalArgumentException e) - { - AELog.error( e ); - } - catch (IllegalAccessException e) - { - AELog.error( e ); - } - - } - - private void updateString(Object oldValue, String val) - { - try - { - this.field.set( this.source, val ); - } - catch (IllegalArgumentException e) - { - AELog.error( e ); - } - catch (IllegalAccessException e) - { - AELog.error( e ); - } - } - - private void updateValue(Object oldValue, long val) - { - try - { - if ( this.field.getType().isEnum() ) - { - EnumSet valList = EnumSet.allOf( (Class) this.field.getType() ); - for (Enum e : valList) - { - if ( e.ordinal() == val ) - { - this.field.set( this.source, e ); - break; - } - } - } - else - { - if ( this.field.getType().equals( int.class ) ) - this.field.set( this.source, (int) val ); - else if ( this.field.getType().equals( long.class ) ) - this.field.set( this.source, val ); - else if ( this.field.getType().equals( boolean.class ) ) - this.field.set( this.source, val == 1 ); - else if ( this.field.getType().equals( Integer.class ) ) - this.field.set( this.source, (int) val ); - else if ( this.field.getType().equals( Long.class ) ) - this.field.set( this.source, val ); - else if ( this.field.getType().equals( Boolean.class ) ) - this.field.set( this.source, val == 1 ); - } - - this.source.onUpdate( this.field.getName(), oldValue, this.field.get( this.source ) ); - } - catch (IllegalArgumentException e) - { - AELog.error( e ); - } - catch (IllegalAccessException e) - { - AELog.error( e ); - } - } - - private void send(ICrafting o, Object val) throws IOException - { - if ( val instanceof String ) - { - if ( o instanceof EntityPlayerMP ) + if( o instanceof EntityPlayerMP ) NetworkHandler.instance.sendTo( new PacketValueConfig( "SyncDat." + this.channel, (String) val ), (EntityPlayerMP) o ); } - else if ( this.field.getType().isEnum() ) + else if( this.field.getType().isEnum() ) { - o.sendProgressBarUpdate( this.source, this.channel, ((Enum) val).ordinal() ); + o.sendProgressBarUpdate( this.source, this.channel, ( (Enum) val ).ordinal() ); } - else if ( val instanceof Long || val.getClass() == long.class ) + else if( val instanceof Long || val.getClass() == long.class ) { NetworkHandler.instance.sendTo( new PacketProgressBar( this.channel, (Long) val ), (EntityPlayerMP) o ); } - else if ( val instanceof Boolean || val.getClass() == boolean.class ) + else if( val instanceof Boolean || val.getClass() == boolean.class ) { - o.sendProgressBarUpdate( this.source, this.channel, ((Boolean) val) ? 1 : 0 ); + o.sendProgressBarUpdate( this.source, this.channel, ( (Boolean) val ) ? 1 : 0 ); } else { @@ -184,4 +104,84 @@ public class SyncData this.clientVersion = val; } + + public void update( Object val ) + { + try + { + Object oldValue = this.field.get( this.source ); + if( val instanceof String ) + this.updateString( oldValue, (String) val ); + else + this.updateValue( oldValue, (Long) val ); + } + catch( IllegalArgumentException e ) + { + AELog.error( e ); + } + catch( IllegalAccessException e ) + { + AELog.error( e ); + } + } + + private void updateString( Object oldValue, String val ) + { + try + { + this.field.set( this.source, val ); + } + catch( IllegalArgumentException e ) + { + AELog.error( e ); + } + catch( IllegalAccessException e ) + { + AELog.error( e ); + } + } + + private void updateValue( Object oldValue, long val ) + { + try + { + if( this.field.getType().isEnum() ) + { + EnumSet valList = EnumSet.allOf( (Class) this.field.getType() ); + for( Enum e : valList ) + { + if( e.ordinal() == val ) + { + this.field.set( this.source, e ); + break; + } + } + } + else + { + if( this.field.getType().equals( int.class ) ) + this.field.set( this.source, (int) val ); + else if( this.field.getType().equals( long.class ) ) + this.field.set( this.source, val ); + else if( this.field.getType().equals( boolean.class ) ) + this.field.set( this.source, val == 1 ); + else if( this.field.getType().equals( Integer.class ) ) + this.field.set( this.source, (int) val ); + else if( this.field.getType().equals( Long.class ) ) + this.field.set( this.source, val ); + else if( this.field.getType().equals( Boolean.class ) ) + this.field.set( this.source, val == 1 ); + } + + this.source.onUpdate( this.field.getName(), oldValue, this.field.get( this.source ) ); + } + catch( IllegalArgumentException e ) + { + AELog.error( e ); + } + catch( IllegalAccessException e ) + { + AELog.error( e ); + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java b/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java index 171d8877b..4a9b2bc6c 100644 --- a/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java +++ b/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import java.util.Iterator; import net.minecraft.entity.player.EntityPlayer; @@ -45,33 +46,32 @@ import appeng.tile.misc.TileCellWorkbench; import appeng.util.Platform; import appeng.util.iterators.NullIterator; + public class ContainerCellWorkbench extends ContainerUpgradeable { final TileCellWorkbench workBench; final AppEngNullInventory ni = new AppEngNullInventory(); + @GuiSync( 2 ) + public CopyMode copyMode = CopyMode.CLEAR_ON_REMOVE; + IInventory UpgradeInventoryWrapper; + ItemStack prevStack = null; + int lastUpgrades = 0; + ItemStack LastCell; - public IInventory getCellUpgradeInventory() + public ContainerCellWorkbench( InventoryPlayer ip, TileCellWorkbench te ) { - IInventory ri = this.workBench.getCellUpgradeInventory(); - return ri == null ? this.ni : ri; + super( ip, te ); + this.workBench = te; } - public void setFuzzy(FuzzyMode valueOf) + public void setFuzzy( FuzzyMode valueOf ) { ICellWorkbenchItem cwi = this.workBench.getCell(); - if ( cwi != null ) + if( cwi != null ) cwi.setFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ), valueOf ); } - private FuzzyMode getFuzzyMode() - { - ICellWorkbenchItem cwi = this.workBench.getCell(); - if ( cwi != null ) - return cwi.getFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ) ); - return FuzzyMode.IGNORE_ALL; - } - public void nextCopyMode() { this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, Platform.nextEnum( this.getCopyMode() ) ); @@ -82,6 +82,161 @@ public class ContainerCellWorkbench extends ContainerUpgradeable return (CopyMode) this.workBench.getConfigManager().getSetting( Settings.COPY_MODE ); } + @Override + protected int getHeight() + { + return 251; + } + + @Override + protected void setupConfig() + { + int x = 8; + int y = 29; + int offset = 0; + + IInventory cell = this.upgradeable.getInventoryByName( "cell" ); + this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.WORKBENCH_CELL, cell, 0, 152, 8, this.invPlayer ) ); + + IInventory inv = this.upgradeable.getInventoryByName( "config" ); + this.UpgradeInventoryWrapper = new Upgrades();// Platform.isServer() ? new Upgrades() : new AppEngInternalInventory( + // null, 3 * 8 ); + + for( int w = 0; w < 7; w++ ) + for( int z = 0; z < 9; z++ ) + { + this.addSlotToContainer( new SlotFakeTypeOnly( inv, offset, x + z * 18, y + w * 18 ) ); + offset++; + } + + for( int zz = 0; zz < 3; zz++ ) + for( int z = 0; z < 8; z++ ) + { + int iSLot = zz * 8 + z; + this.addSlotToContainer( new OptionalSlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, this.UpgradeInventoryWrapper, this, iSLot, 187 + zz * 18, 8 + 18 * z, iSLot, this.invPlayer ) ); + } + /* + * if ( supportCapacity() ) { for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new + * OptionalSlotFakeTypeOnly( inv, this, offset++, x, y, z, w, 1 ) ); + * + * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( + * inv, this, offset++, x, y, z, w + 2, 2 ) ); + * + * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( + * inv, this, offset++, x, y, z, w + 4, 3 ) ); } + */ + } + + @Override + public int availableUpgrades() + { + ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); + if( this.prevStack != is ) + { + this.prevStack = is; + return this.lastUpgrades = this.getCellUpgradeInventory().getSizeInventory(); + } + return this.lastUpgrades; + } + + @Override + public void detectAndSendChanges() + { + ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); + if( Platform.isServer() ) + { + for( Object crafter : this.crafters ) + { + ICrafting icrafting = (ICrafting) crafter; + + if( this.prevStack != is ) + { + // if the bars changed an item was probably made, so just send shit! + for( Object s : this.inventorySlots ) + { + if( s instanceof OptionalSlotRestrictedInput ) + { + OptionalSlotRestrictedInput sri = (OptionalSlotRestrictedInput) s; + icrafting.sendSlotContents( this, sri.slotNumber, sri.getStack() ); + } + } + ( (EntityPlayerMP) icrafting ).isChangingQuantityOnly = false; + } + } + + this.copyMode = this.getCopyMode(); + this.fzMode = this.getFuzzyMode(); + } + + this.prevStack = is; + this.standardDetectAndSendChanges(); + } + + @Override + public boolean isSlotEnabled( int idx ) + { + return idx < this.availableUpgrades(); + } + + public IInventory getCellUpgradeInventory() + { + IInventory ri = this.workBench.getCellUpgradeInventory(); + return ri == null ? this.ni : ri; + } + + @Override + public void onUpdate( String field, Object oldValue, Object newValue ) + { + if( field.equals( "copyMode" ) ) + this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, this.copyMode ); + + super.onUpdate( field, oldValue, newValue ); + } + + public void clear() + { + IInventory inv = this.upgradeable.getInventoryByName( "config" ); + for( int x = 0; x < inv.getSizeInventory(); x++ ) + inv.setInventorySlotContents( x, null ); + this.detectAndSendChanges(); + } + + private FuzzyMode getFuzzyMode() + { + ICellWorkbenchItem cwi = this.workBench.getCell(); + if( cwi != null ) + return cwi.getFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ) ); + return FuzzyMode.IGNORE_ALL; + } + + public void partition() + { + IInventory inv = this.upgradeable.getInventoryByName( "config" ); + + IMEInventory cellInv = AEApi.instance().registries().cell().getCellInventory( this.upgradeable.getInventoryByName( "cell" ).getStackInSlot( 0 ), null, StorageChannel.ITEMS ); + + Iterator i = new NullIterator(); + if( cellInv != null ) + { + IItemList list = cellInv.getAvailableItems( AEApi.instance().storage().createItemList() ); + i = list.iterator(); + } + + for( int x = 0; x < inv.getSizeInventory(); x++ ) + { + if( i.hasNext() ) + { + ItemStack g = i.next().getItemStack(); + g.stackSize = 1; + inv.setInventorySlotContents( x, g ); + } + else + inv.setInventorySlotContents( x, null ); + } + + this.detectAndSendChanges(); + } + class Upgrades implements IInventory { @@ -92,13 +247,13 @@ public class ContainerCellWorkbench extends ContainerUpgradeable } @Override - public ItemStack getStackInSlot(int i) + public ItemStack getStackInSlot( int i ) { return ContainerCellWorkbench.this.getCellUpgradeInventory().getStackInSlot( i ); } @Override - public ItemStack decrStackSize(int i, int j) + public ItemStack decrStackSize( int i, int j ) { IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); ItemStack is = inv.decrStackSize( i, j ); @@ -107,7 +262,7 @@ public class ContainerCellWorkbench extends ContainerUpgradeable } @Override - public ItemStack getStackInSlotOnClosing(int i) + public ItemStack getStackInSlotOnClosing( int i ) { IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); ItemStack is = inv.getStackInSlotOnClosing( i ); @@ -116,7 +271,7 @@ public class ContainerCellWorkbench extends ContainerUpgradeable } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public void setInventorySlotContents( int i, ItemStack itemstack ) { IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); inv.setInventorySlotContents( i, itemstack ); @@ -148,7 +303,7 @@ public class ContainerCellWorkbench extends ContainerUpgradeable } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) + public boolean isUseableByPlayer( EntityPlayer entityplayer ) { return false; } @@ -164,168 +319,9 @@ public class ContainerCellWorkbench extends ContainerUpgradeable } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { return ContainerCellWorkbench.this.getCellUpgradeInventory().isItemValidForSlot( i, itemstack ); } } - - IInventory UpgradeInventoryWrapper; - - ItemStack prevStack = null; - int lastUpgrades = 0; - - @GuiSync(2) - public CopyMode copyMode = CopyMode.CLEAR_ON_REMOVE; - - public ContainerCellWorkbench(InventoryPlayer ip, TileCellWorkbench te) { - super( ip, te ); - this.workBench = te; - } - - @Override - protected int getHeight() - { - return 251; - } - - @Override - public int availableUpgrades() - { - ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); - if ( this.prevStack != is ) - { - this.prevStack = is; - return this.lastUpgrades = this.getCellUpgradeInventory().getSizeInventory(); - } - return this.lastUpgrades; - } - - @Override - public boolean isSlotEnabled(int idx) - { - return idx < this.availableUpgrades(); - } - - @Override - protected void setupConfig() - { - int x = 8; - int y = 29; - int offset = 0; - - IInventory cell = this.upgradeable.getInventoryByName( "cell" ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.WORKBENCH_CELL, cell, 0, 152, 8, this.invPlayer ) ); - - IInventory inv = this.upgradeable.getInventoryByName( "config" ); - this.UpgradeInventoryWrapper = new Upgrades();// Platform.isServer() ? new Upgrades() : new AppEngInternalInventory( - // null, 3 * 8 ); - - for (int w = 0; w < 7; w++) - for (int z = 0; z < 9; z++) - { - this.addSlotToContainer( new SlotFakeTypeOnly( inv, offset, x + z * 18, y + w * 18 ) ); - offset++; - } - - for (int zz = 0; zz < 3; zz++) - for (int z = 0; z < 8; z++) - { - int iSLot = zz * 8 + z; - this.addSlotToContainer( new OptionalSlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, this.UpgradeInventoryWrapper, this, iSLot, 187 + zz * 18, - 8 + 18 * z, iSLot, this.invPlayer ) ); - } - /* - * if ( supportCapacity() ) { for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new - * OptionalSlotFakeTypeOnly( inv, this, offset++, x, y, z, w, 1 ) ); - * - * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( - * inv, this, offset++, x, y, z, w + 2, 2 ) ); - * - * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( - * inv, this, offset++, x, y, z, w + 4, 3 ) ); } - */ - } - - ItemStack LastCell; - - @Override - public void onUpdate(String field, Object oldValue, Object newValue) - { - if ( field.equals( "copyMode" ) ) - this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, this.copyMode ); - - super.onUpdate( field, oldValue, newValue ); - } - - @Override - public void detectAndSendChanges() - { - ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); - if ( Platform.isServer() ) - { - for (Object crafter : this.crafters) - { - ICrafting icrafting = (ICrafting) crafter; - - if ( this.prevStack != is ) - { - // if the bars changed an item was probably made, so just send shit! - for (Object s : this.inventorySlots) - { - if ( s instanceof OptionalSlotRestrictedInput ) - { - OptionalSlotRestrictedInput sri = (OptionalSlotRestrictedInput) s; - icrafting.sendSlotContents( this, sri.slotNumber, sri.getStack() ); - } - } - ((EntityPlayerMP) icrafting).isChangingQuantityOnly = false; - } - } - - this.copyMode = this.getCopyMode(); - this.fzMode = this.getFuzzyMode(); - } - - this.prevStack = is; - this.standardDetectAndSendChanges(); - } - - public void clear() - { - IInventory inv = this.upgradeable.getInventoryByName( "config" ); - for (int x = 0; x < inv.getSizeInventory(); x++) - inv.setInventorySlotContents( x, null ); - this.detectAndSendChanges(); - } - - public void partition() - { - IInventory inv = this.upgradeable.getInventoryByName( "config" ); - - IMEInventory cellInv = AEApi.instance().registries().cell() - .getCellInventory( this.upgradeable.getInventoryByName( "cell" ).getStackInSlot( 0 ), null, StorageChannel.ITEMS ); - - Iterator i = new NullIterator(); - if ( cellInv != null ) - { - IItemList list = cellInv.getAvailableItems( AEApi.instance().storage().createItemList() ); - i = list.iterator(); - } - - for (int x = 0; x < inv.getSizeInventory(); x++) - { - if ( i.hasNext() ) - { - ItemStack g = i.next().getItemStack(); - g.stackSize = 1; - inv.setInventorySlotContents( x, g ); - } - else - inv.setInventorySlotContents( x, null ); - } - - this.detectAndSendChanges(); - } - } diff --git a/src/main/java/appeng/container/implementations/ContainerChest.java b/src/main/java/appeng/container/implementations/ContainerChest.java index 58caf9264..0100f98fe 100644 --- a/src/main/java/appeng/container/implementations/ContainerChest.java +++ b/src/main/java/appeng/container/implementations/ContainerChest.java @@ -18,18 +18,21 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileChest; + public class ContainerChest extends AEBaseContainer { final TileChest chest; - public ContainerChest(InventoryPlayer ip, TileChest chest) { + public ContainerChest( InventoryPlayer ip, TileChest chest ) + { super( ip, chest, null ); this.chest = chest; @@ -37,5 +40,4 @@ public class ContainerChest extends AEBaseContainer this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); } - } diff --git a/src/main/java/appeng/container/implementations/ContainerCondenser.java b/src/main/java/appeng/container/implementations/ContainerCondenser.java index 379f5a5ed..941462236 100644 --- a/src/main/java/appeng/container/implementations/ContainerCondenser.java +++ b/src/main/java/appeng/container/implementations/ContainerCondenser.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.api.config.CondenserOutput; @@ -30,18 +31,26 @@ import appeng.container.slot.SlotRestrictedInput; import appeng.tile.misc.TileCondenser; import appeng.util.Platform; + public class ContainerCondenser extends AEBaseContainer implements IProgressProvider { final TileCondenser condenser; + @GuiSync( 0 ) + public long requiredEnergy = 0; + @GuiSync( 1 ) + public long storedPower = 0; + @GuiSync( 2 ) + public CondenserOutput output = CondenserOutput.TRASH; - public ContainerCondenser(InventoryPlayer ip, TileCondenser condenser) { + public ContainerCondenser( InventoryPlayer ip, TileCondenser condenser ) + { super( ip, condenser, null ); this.condenser = condenser; this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.TRASH, condenser, 0, 51, 52, ip ) ); this.addSlotToContainer( new SlotOutput( condenser, 1, 105, 52, -1 ) ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_COMPONENT, condenser.getInternalInventory(), 2, 101, 26, ip )).setStackLimit( 1 ) ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_COMPONENT, condenser.getInternalInventory(), 2, 101, 26, ip ) ).setStackLimit( 1 ) ); this.bindPlayerInventory( ip, 0, 197 - /* height of player inventory */82 ); } @@ -49,7 +58,7 @@ public class ContainerCondenser extends AEBaseContainer implements IProgressProv @Override public void detectAndSendChanges() { - if ( Platform.isServer() ) + if( Platform.isServer() ) { double maxStorage = this.condenser.getStorage(); double requiredEnergy = this.condenser.getRequiredPower(); @@ -62,15 +71,6 @@ public class ContainerCondenser extends AEBaseContainer implements IProgressProv super.detectAndSendChanges(); } - @GuiSync(0) - public long requiredEnergy = 0; - - @GuiSync(1) - public long storedPower = 0; - - @GuiSync(2) - public CondenserOutput output = CondenserOutput.TRASH; - @Override public int getCurrentProgress() { @@ -82,5 +82,4 @@ public class ContainerCondenser extends AEBaseContainer implements IProgressProv { return (int) this.requiredEnergy; } - } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftAmount.java b/src/main/java/appeng/container/implementations/ContainerCraftAmount.java index 127a3d199..ed5123522 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftAmount.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftAmount.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.world.World; @@ -33,15 +34,16 @@ import appeng.container.AEBaseContainer; import appeng.container.slot.SlotInaccessible; import appeng.tile.inventory.AppEngInternalInventory; + public class ContainerCraftAmount extends AEBaseContainer { - final ITerminalHost priHost; - - public IAEItemStack whatToMake; public final Slot craftingItem; + final ITerminalHost priHost; + public IAEItemStack whatToMake; - public ContainerCraftAmount(InventoryPlayer ip, ITerminalHost te) { + public ContainerCraftAmount( InventoryPlayer ip, ITerminalHost te ) + { super( ip, te ); this.priHost = te; @@ -58,7 +60,7 @@ public class ContainerCraftAmount extends AEBaseContainer public IGrid getGrid() { - IActionHost h = ((IActionHost) this.getTarget()); + IActionHost h = ( (IActionHost) this.getTarget() ); return h.getActionableNode().getGrid(); } @@ -71,5 +73,4 @@ public class ContainerCraftAmount extends AEBaseContainer { return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); } - } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java b/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java index 1ef773300..8b5a36aa0 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java @@ -18,13 +18,12 @@ package appeng.container.implementations; + import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.Future; -import com.google.common.collect.ImmutableSet; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; @@ -33,6 +32,8 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; +import com.google.common.collect.ImmutableSet; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -62,78 +63,51 @@ import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartTerminal; import appeng.util.Platform; + public class ContainerCraftConfirm extends AEBaseContainer { + public final ArrayList cpus = new ArrayList(); final ITerminalHost priHost; public Future job; public ICraftingJob result; - - @GuiSync(0) + @GuiSync( 0 ) public long bytesUsed; - - @GuiSync(1) + @GuiSync( 1 ) public long cpuBytesAvail; - - @GuiSync(2) + @GuiSync( 2 ) public int cpuCoProcessors; - - @GuiSync(3) + @GuiSync( 3 ) public boolean autoStart = false; - - @GuiSync(4) + @GuiSync( 4 ) public boolean simulation = true; - - @GuiSync(5) + @GuiSync( 5 ) public int selectedCpu = -1; - - @GuiSync(6) + @GuiSync( 6 ) public boolean noCPU = true; - - @GuiSync(7) + @GuiSync( 7 ) public String myName = ""; - protected long cpuIdx = Long.MIN_VALUE; - public final ArrayList cpus = new ArrayList(); - - public ContainerCraftConfirm(InventoryPlayer ip, ITerminalHost te) { + public ContainerCraftConfirm( InventoryPlayer ip, ITerminalHost te ) + { super( ip, te ); this.priHost = te; } - private void sendCPUs() + public void cycleCpu( boolean next ) { - Collections.sort( this.cpus ); - - if ( this.selectedCpu >= this.cpus.size() ) - { - this.selectedCpu = -1; - this.cpuBytesAvail = 0; - this.cpuCoProcessors = 0; - this.myName = ""; - } - else if ( this.selectedCpu != -1 ) - { - this.myName = this.cpus.get( this.selectedCpu ).myName; - this.cpuBytesAvail = this.cpus.get( this.selectedCpu ).size; - this.cpuCoProcessors = this.cpus.get( this.selectedCpu ).processors; - } - } - - public void cycleCpu(boolean next) - { - if ( next ) + if( next ) this.selectedCpu++; else this.selectedCpu--; - if ( this.selectedCpu < -1 ) + if( this.selectedCpu < -1 ) this.selectedCpu = this.cpus.size() - 1; - else if ( this.selectedCpu >= this.cpus.size() ) + else if( this.selectedCpu >= this.cpus.size() ) this.selectedCpu = -1; - if ( this.selectedCpu == -1 ) + if( this.selectedCpu == -1 ) { this.cpuBytesAvail = 0; this.cpuCoProcessors = 0; @@ -150,7 +124,7 @@ public class ContainerCraftConfirm extends AEBaseContainer @Override public void detectAndSendChanges() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); @@ -158,28 +132,28 @@ public class ContainerCraftConfirm extends AEBaseContainer int matches = 0; boolean changed = false; - for (ICraftingCPU c : cpuSet) + for( ICraftingCPU c : cpuSet ) { boolean found = false; - for (CraftingCPURecord ccr : this.cpus) - if ( ccr.cpu == c ) + for( CraftingCPURecord ccr : this.cpus ) + if( ccr.cpu == c ) found = true; boolean matched = this.cpuMatches( c ); - if ( matched ) + if( matched ) matches++; - if ( found == !matched ) + if( found == !matched ) changed = true; } - if ( changed || this.cpus.size() != matches ) + if( changed || this.cpus.size() != matches ) { this.cpus.clear(); - for (ICraftingCPU c : cpuSet) + for( ICraftingCPU c : cpuSet ) { - if ( this.cpuMatches( c ) ) + if( this.cpuMatches( c ) ) this.cpus.add( new CraftingCPURecord( c.getAvailableStorage(), c.getCoProcessors(), c ) ); } @@ -190,16 +164,16 @@ public class ContainerCraftConfirm extends AEBaseContainer super.detectAndSendChanges(); - if ( this.job != null && this.job.isDone() ) + if( this.job != null && this.job.isDone() ) { try { this.result = this.job.get(); - if ( !this.result.isSimulation() ) + if( !this.result.isSimulation() ) { this.simulation = false; - if ( this.autoStart ) + if( this.autoStart ) { this.startJob(); return; @@ -219,7 +193,7 @@ public class ContainerCraftConfirm extends AEBaseContainer this.bytesUsed = this.result.getByteTotal(); - for (IAEItemStack out : plan) + for( IAEItemStack out : plan ) { IAEItemStack m = null; @@ -234,12 +208,12 @@ public class ContainerCraftConfirm extends AEBaseContainer IStorageGrid sg = this.getGrid().getCache( IStorageGrid.class ); IMEInventory items = sg.getItemInventory(); - if ( c != null && this.result.isSimulation() ) + if( c != null && this.result.isSimulation() ) { m = o.copy(); o = items.extractItems( o, Actionable.SIMULATE, this.mySrc ); - if ( o == null ) + if( o == null ) { o = m.copy(); o.setStackSize( 0 ); @@ -248,33 +222,33 @@ public class ContainerCraftConfirm extends AEBaseContainer m.setStackSize( m.getStackSize() - o.getStackSize() ); } - if ( o.getStackSize() > 0 ) + if( o.getStackSize() > 0 ) a.appendItem( o ); - if ( p.getStackSize() > 0 ) + if( p.getStackSize() > 0 ) b.appendItem( p ); - if ( c != null && m != null && m.getStackSize() > 0 ) + if( c != null && m != null && m.getStackSize() > 0 ) c.appendItem( m ); } - for (Object g : this.crafters) + for( Object g : this.crafters ) { - if ( g instanceof EntityPlayer ) + if( g instanceof EntityPlayer ) { NetworkHandler.instance.sendTo( a, (EntityPlayerMP) g ); NetworkHandler.instance.sendTo( b, (EntityPlayerMP) g ); - if ( c != null ) + if( c != null ) NetworkHandler.instance.sendTo( c, (EntityPlayerMP) g ); } } } - catch (IOException e) + catch( IOException e ) { // :P } } - catch (Throwable e) + catch( Throwable e ) { this.getPlayerInv().player.addChatMessage( new ChatComponentText( "Error: " + e.toString() ) ); AELog.error( e ); @@ -287,34 +261,59 @@ public class ContainerCraftConfirm extends AEBaseContainer this.verifyPermissions( SecurityPermissions.CRAFT, false ); } - private boolean cpuMatches(ICraftingCPU c) + public IGrid getGrid() + { + IActionHost h = ( (IActionHost) this.getTarget() ); + return h.getActionableNode().getGrid(); + } + + private boolean cpuMatches( ICraftingCPU c ) { return c.getAvailableStorage() >= this.bytesUsed && !c.isBusy(); } + private void sendCPUs() + { + Collections.sort( this.cpus ); + + if( this.selectedCpu >= this.cpus.size() ) + { + this.selectedCpu = -1; + this.cpuBytesAvail = 0; + this.cpuCoProcessors = 0; + this.myName = ""; + } + else if( this.selectedCpu != -1 ) + { + this.myName = this.cpus.get( this.selectedCpu ).myName; + this.cpuBytesAvail = this.cpus.get( this.selectedCpu ).size; + this.cpuCoProcessors = this.cpus.get( this.selectedCpu ).processors; + } + } + public void startJob() { GuiBridge OriginalGui = null; IActionHost ah = this.getActionHost(); - if ( ah instanceof WirelessTerminalGuiObject ) + if( ah instanceof WirelessTerminalGuiObject ) OriginalGui = GuiBridge.GUI_WIRELESS_TERM; - if ( ah instanceof PartTerminal ) + if( ah instanceof PartTerminal ) OriginalGui = GuiBridge.GUI_ME; - if ( ah instanceof PartCraftingTerminal ) + if( ah instanceof PartCraftingTerminal ) OriginalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - if ( ah instanceof PartPatternTerminal ) + if( ah instanceof PartPatternTerminal ) OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL; - if ( this.result != null && !this.simulation ) + if( this.result != null && !this.simulation ) { ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); ICraftingLink g = cc.submitJob( this.result, null, this.selectedCpu == -1 ? null : this.cpus.get( this.selectedCpu ).cpu, true, this.getActionSrc() ); this.autoStart = false; - if ( g != null && OriginalGui != null && this.openContext != null ) + if( g != null && OriginalGui != null && this.openContext != null ) { NetworkHandler.instance.sendTo( new PacketSwitchGuis( OriginalGui ), (EntityPlayerMP) this.invPlayer.player ); @@ -324,41 +323,35 @@ public class ContainerCraftConfirm extends AEBaseContainer } } - @Override - public void onContainerClosed(EntityPlayer par1EntityPlayer) + public BaseActionSource getActionSrc() { - super.onContainerClosed( par1EntityPlayer ); - if ( this.job != null ) - { - this.job.cancel( true ); - this.job = null; - } + return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); } @Override - public void removeCraftingFromCrafters(ICrafting c) + public void removeCraftingFromCrafters( ICrafting c ) { super.removeCraftingFromCrafters( c ); - if ( this.job != null ) + if( this.job != null ) { this.job.cancel( true ); this.job = null; } } - public IGrid getGrid() + @Override + public void onContainerClosed( EntityPlayer par1EntityPlayer ) { - IActionHost h = ((IActionHost) this.getTarget()); - return h.getActionableNode().getGrid(); + super.onContainerClosed( par1EntityPlayer ); + if( this.job != null ) + { + this.job.cancel( true ); + this.job = null; + } } public World getWorld() { return this.getPlayerInv().player.worldObj; } - - public BaseActionSource getActionSrc() - { - return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); - } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java b/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java index 0eb1d1001..89e517559 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; @@ -47,62 +48,74 @@ import appeng.me.cluster.implementations.CraftingCPUCluster; import appeng.tile.crafting.TileCraftingTile; import appeng.util.Platform; + public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorHandlerReceiver, ICustomNameObject { + final IItemList list = AEApi.instance().storage().createItemList(); + protected IGrid network; CraftingCPUCluster monitor = null; String cpuName = null; - protected IGrid network; + int delay = 40; - final IItemList list = AEApi.instance().storage().createItemList(); - - public ContainerCraftingCPU(InventoryPlayer ip, Object te) { + public ContainerCraftingCPU( InventoryPlayer ip, Object te ) + { super( ip, te ); - IGridHost host = (IGridHost) (te instanceof IGridHost ? te : null); + IGridHost host = (IGridHost) ( te instanceof IGridHost ? te : null ); - if ( host != null ) + if( host != null ) { this.findNode( host, ForgeDirection.UNKNOWN ); - for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) this.findNode( host, d ); } - if ( te instanceof TileCraftingTile ) - this.setCPU( (ICraftingCPU) ((TileCraftingTile) te).getCluster() ); + if( te instanceof TileCraftingTile ) + this.setCPU( (ICraftingCPU) ( (TileCraftingTile) te ).getCluster() ); - if ( this.network == null && Platform.isServer() ) + if( this.network == null && Platform.isServer() ) this.isContainerValid = false; } - protected void setCPU(ICraftingCPU c) + private void findNode( IGridHost host, ForgeDirection d ) { - if ( c == this.monitor ) + if( this.network == null ) + { + IGridNode node = host.getGridNode( d ); + if( node != null ) + this.network = node.getGrid(); + } + } + + protected void setCPU( ICraftingCPU c ) + { + if( c == this.monitor ) return; - if ( this.monitor != null ) + if( this.monitor != null ) this.monitor.removeListener( this ); - for (Object g : this.crafters) + for( Object g : this.crafters ) { - if ( g instanceof EntityPlayer ) + if( g instanceof EntityPlayer ) { try { NetworkHandler.instance.sendTo( new PacketValueConfig( "CraftingStatus", "Clear" ), (EntityPlayerMP) g ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } } } - if ( c instanceof CraftingCPUCluster ) + if( c instanceof CraftingCPUCluster ) { this.cpuName = c.getName(); this.monitor = (CraftingCPUCluster) c; - if ( this.monitor != null ) + if( this.monitor != null ) { this.list.resetStatus(); this.monitor.getListOfItem( this.list, CraftingItemList.ALL ); @@ -118,45 +131,33 @@ public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorH public void cancelCrafting() { - if ( this.monitor != null ) + if( this.monitor != null ) { this.monitor.cancel(); } } - private void findNode(IGridHost host, ForgeDirection d) - { - if ( this.network == null ) - { - IGridNode node = host.getGridNode( d ); - if ( node != null ) - this.network = node.getGrid(); - } - } - - int delay = 40; - @Override - public void onContainerClosed(EntityPlayer player) + public void removeCraftingFromCrafters( ICrafting c ) { - super.onContainerClosed( player ); - if ( this.monitor != null ) + super.removeCraftingFromCrafters( c ); + + if( this.crafters.isEmpty() && this.monitor != null ) this.monitor.removeListener( this ); } @Override - public void removeCraftingFromCrafters(ICrafting c) + public void onContainerClosed( EntityPlayer player ) { - super.removeCraftingFromCrafters( c ); - - if ( this.crafters.isEmpty() && this.monitor != null ) + super.onContainerClosed( player ); + if( this.monitor != null ) this.monitor.removeListener( this ); } @Override public void detectAndSendChanges() { - if ( Platform.isServer() && this.monitor != null && !this.list.isEmpty() ) + if( Platform.isServer() && this.monitor != null && !this.list.isEmpty() ) { try { @@ -164,7 +165,7 @@ public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorH PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 ); - for (IAEItemStack out : this.list) + for( IAEItemStack out : this.list ) { a.appendItem( this.monitor.getItemStack( out, CraftingItemList.STORAGE ) ); b.appendItem( this.monitor.getItemStack( out, CraftingItemList.ACTIVE ) ); @@ -173,40 +174,39 @@ public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorH this.list.resetStatus(); - for (Object g : this.crafters) + for( Object g : this.crafters ) { - if ( g instanceof EntityPlayer ) + if( g instanceof EntityPlayer ) { - if ( !a.isEmpty() ) + if( !a.isEmpty() ) NetworkHandler.instance.sendTo( a, (EntityPlayerMP) g ); - if ( !b.isEmpty() ) + if( !b.isEmpty() ) NetworkHandler.instance.sendTo( b, (EntityPlayerMP) g ); - if ( !c.isEmpty() ) + if( !c.isEmpty() ) NetworkHandler.instance.sendTo( c, (EntityPlayerMP) g ); } } } - catch (IOException e) + catch( IOException e ) { // :P } - } super.detectAndSendChanges(); } @Override - public boolean isValid(Object verificationToken) + public boolean isValid( Object verificationToken ) { return true; } @Override - public void postChange(IBaseMonitor monitor, Iterable change, BaseActionSource actionSource) + public void postChange( IBaseMonitor monitor, Iterable change, BaseActionSource actionSource ) { - for (IAEItemStack is : change) + for( IAEItemStack is : change ) { is = is.copy(); is.setStackSize( 1 ); diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java b/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java index 8f8115b5a..b505fd6c7 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java @@ -18,56 +18,34 @@ package appeng.container.implementations; + import java.util.ArrayList; import java.util.Collections; -import com.google.common.collect.ImmutableSet; - import net.minecraft.entity.player.InventoryPlayer; +import com.google.common.collect.ImmutableSet; + import appeng.api.networking.crafting.ICraftingCPU; import appeng.api.networking.crafting.ICraftingGrid; import appeng.api.storage.ITerminalHost; import appeng.container.guisync.GuiSync; + public class ContainerCraftingStatus extends ContainerCraftingCPU { - @GuiSync(5) + public final ArrayList cpus = new ArrayList(); + @GuiSync( 5 ) public int selectedCpu = -1; - - @GuiSync(6) + @GuiSync( 6 ) public boolean noCPU = true; - - @GuiSync(7) + @GuiSync( 7 ) public String myName = ""; - public final ArrayList cpus = new ArrayList(); - - private void sendCPUs() + public ContainerCraftingStatus( InventoryPlayer ip, ITerminalHost te ) { - Collections.sort( this.cpus ); - - if ( this.selectedCpu >= this.cpus.size() ) - { - this.selectedCpu = -1; - this.myName = ""; - } - else if ( this.selectedCpu != -1 ) - { - this.myName = this.cpus.get( this.selectedCpu ).myName; - } - - if ( this.selectedCpu == -1 && this.cpus.size() > 0 ) - this.selectedCpu = 0; - - if ( this.selectedCpu != -1 ) - { - if ( this.cpus.get( this.selectedCpu ).cpu != this.monitor ) - this.setCPU( this.cpus.get( this.selectedCpu ).cpu ); - } - else - this.setCPU( null ); + super( ip, te ); } @Override @@ -78,28 +56,28 @@ public class ContainerCraftingStatus extends ContainerCraftingCPU int matches = 0; boolean changed = false; - for (ICraftingCPU c : cpuSet) + for( ICraftingCPU c : cpuSet ) { boolean found = false; - for (CraftingCPURecord ccr : this.cpus) - if ( ccr.cpu == c ) + for( CraftingCPURecord ccr : this.cpus ) + if( ccr.cpu == c ) found = true; boolean matched = this.cpuMatches( c ); - if ( matched ) + if( matched ) matches++; - if ( found == !matched ) + if( found == !matched ) changed = true; } - if ( changed || this.cpus.size() != matches ) + if( changed || this.cpus.size() != matches ) { this.cpus.clear(); - for (ICraftingCPU c : cpuSet) + for( ICraftingCPU c : cpuSet ) { - if ( this.cpuMatches( c ) ) + if( this.cpuMatches( c ) ) this.cpus.add( new CraftingCPURecord( c.getAvailableStorage(), c.getCoProcessors(), c ) ); } @@ -111,31 +89,53 @@ public class ContainerCraftingStatus extends ContainerCraftingCPU super.detectAndSendChanges(); } - private boolean cpuMatches(ICraftingCPU c) + private boolean cpuMatches( ICraftingCPU c ) { return c.isBusy(); } - public ContainerCraftingStatus(InventoryPlayer ip, ITerminalHost te) { - super( ip, te ); + private void sendCPUs() + { + Collections.sort( this.cpus ); + + if( this.selectedCpu >= this.cpus.size() ) + { + this.selectedCpu = -1; + this.myName = ""; + } + else if( this.selectedCpu != -1 ) + { + this.myName = this.cpus.get( this.selectedCpu ).myName; + } + + if( this.selectedCpu == -1 && this.cpus.size() > 0 ) + this.selectedCpu = 0; + + if( this.selectedCpu != -1 ) + { + if( this.cpus.get( this.selectedCpu ).cpu != this.monitor ) + this.setCPU( this.cpus.get( this.selectedCpu ).cpu ); + } + else + this.setCPU( null ); } - public void cycleCpu(boolean next) + public void cycleCpu( boolean next ) { - if ( next ) + if( next ) this.selectedCpu++; else this.selectedCpu--; - if ( this.selectedCpu < -1 ) + if( this.selectedCpu < -1 ) this.selectedCpu = this.cpus.size() - 1; - else if ( this.selectedCpu >= this.cpus.size() ) + else if( this.selectedCpu >= this.cpus.size() ) this.selectedCpu = -1; - if ( this.selectedCpu == -1 && this.cpus.size() > 0 ) + if( this.selectedCpu == -1 && this.cpus.size() > 0 ) this.selectedCpu = 0; - if ( this.selectedCpu == -1 ) + if( this.selectedCpu == -1 ) { this.myName = ""; this.setCPU( null ); @@ -146,5 +146,4 @@ public class ContainerCraftingStatus extends ContainerCraftingCPU this.setCPU( this.cpus.get( this.selectedCpu ).cpu ); } } - } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java b/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java index a47d7b13b..28d27baee 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; @@ -34,39 +35,24 @@ import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.IAEAppEngInventory; import appeng.tile.inventory.InvOperation; + public class ContainerCraftingTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IContainerCraftingPacket { + public final PartCraftingTerminal ct; final AppEngInternalInventory output = new AppEngInternalInventory( this, 1 ); - final SlotCraftingMatrix[] craftingSlots = new SlotCraftingMatrix[9]; final SlotCraftingTerm outputSlot; - public final PartCraftingTerminal ct; - - /** - * Callback for when the crafting matrix is changed. - */ - @Override - public void onCraftMatrixChanged(IInventory par1IInventory) + public ContainerCraftingTerm( InventoryPlayer ip, ITerminalHost monitorable ) { - ContainerNull cn = new ContainerNull(); - InventoryCrafting ic = new InventoryCrafting( cn, 3, 3 ); - - for (int x = 0; x < 9; x++) - ic.setInventorySlotContents( x, this.craftingSlots[x].getStack() ); - - this.outputSlot.putStack( CraftingManager.getInstance().findMatchingRecipe( ic, this.getPlayerInv().player.worldObj ) ); - } - - public ContainerCraftingTerm(InventoryPlayer ip, ITerminalHost monitorable) { super( ip, monitorable, false ); this.ct = (PartCraftingTerminal) monitorable; IInventory crafting = this.ct.getInventoryByName( "crafting" ); - for (int y = 0; y < 3; y++) - for (int x = 0; x < 3; x++) + for( int y = 0; y < 3; y++ ) + for( int x = 0; x < 3; x++ ) this.addSlotToContainer( this.craftingSlots[x + y * 3] = new SlotCraftingMatrix( this, crafting, x + y * 3, 37 + x * 18, -72 + y * 18 ) ); this.addSlotToContainer( this.outputSlot = new SlotCraftingTerm( this.getPlayerInv().player, this.mySrc, this.powerSrc, monitorable, crafting, crafting, this.output, 131, -72 + 18, this ) ); @@ -76,6 +62,21 @@ public class ContainerCraftingTerm extends ContainerMEMonitorable implements IAE this.onCraftMatrixChanged( crafting ); } + /** + * Callback for when the crafting matrix is changed. + */ + @Override + public void onCraftMatrixChanged( IInventory par1IInventory ) + { + ContainerNull cn = new ContainerNull(); + InventoryCrafting ic = new InventoryCrafting( cn, 3, 3 ); + + for( int x = 0; x < 9; x++ ) + ic.setInventorySlotContents( x, this.craftingSlots[x].getStack() ); + + this.outputSlot.putStack( CraftingManager.getInstance().findMatchingRecipe( ic, this.getPlayerInv().player.worldObj ) ); + } + @Override public void saveChanges() { @@ -83,15 +84,15 @@ public class ContainerCraftingTerm extends ContainerMEMonitorable implements IAE } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) { } @Override - public IInventory getInventoryByName(String name) + public IInventory getInventoryByName( String name ) { - if (name.equals("player")) + if( name.equals( "player" ) ) { return this.invPlayer; } diff --git a/src/main/java/appeng/container/implementations/ContainerDrive.java b/src/main/java/appeng/container/implementations/ContainerDrive.java index 1ad242e74..c53636b1d 100644 --- a/src/main/java/appeng/container/implementations/ContainerDrive.java +++ b/src/main/java/appeng/container/implementations/ContainerDrive.java @@ -18,28 +18,30 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileDrive; + public class ContainerDrive extends AEBaseContainer { final TileDrive drive; - public ContainerDrive(InventoryPlayer ip, TileDrive drive) { + public ContainerDrive( InventoryPlayer ip, TileDrive drive ) + { super( ip, drive, null ); this.drive = drive; - for (int y = 0; y < 5; y++) - for (int x = 0; x < 2; x++) + for( int y = 0; y < 5; y++ ) + for( int x = 0; x < 2; x++ ) { this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, drive, x + y * 2, 71 + x * 18, 14 + y * 18, this.invPlayer ) ); } this.bindPlayerInventory( ip, 0, 199 - /* height of player inventory */82 ); } - } diff --git a/src/main/java/appeng/container/implementations/ContainerFormationPlane.java b/src/main/java/appeng/container/implementations/ContainerFormationPlane.java index 1c6227168..7625031ba 100644 --- a/src/main/java/appeng/container/implementations/ContainerFormationPlane.java +++ b/src/main/java/appeng/container/implementations/ContainerFormationPlane.java @@ -55,26 +55,6 @@ public class ContainerFormationPlane extends ContainerUpgradeable return 251; } - @Override - public int availableUpgrades() - { - return 5; - } - - @Override - protected boolean supportCapacity() - { - return true; - } - - @Override - public boolean isSlotEnabled( int idx ) - { - int upgrades = this.upgradeable.getInstalledUpgrades( Upgrades.CAPACITY ); - - return upgrades > idx; - } - @Override protected void setupConfig() { @@ -82,11 +62,11 @@ public class ContainerFormationPlane extends ContainerUpgradeable int yo = 23 + 6; IInventory config = this.upgradeable.getInventoryByName( "config" ); - for ( int y = 0; y < 7; y++ ) + for( int y = 0; y < 7; y++ ) { - for ( int x = 0; x < 9; x++ ) + for( int x = 0; x < 9; x++ ) { - if ( y < 2 ) + if( y < 2 ) this.addSlotToContainer( new SlotFakeTypeOnly( config, y * 9 + x, xo + x * 18, yo + y * 18 ) ); else this.addSlotToContainer( new OptionalSlotFakeTypeOnly( config, this, y * 9 + x, xo, yo, x, y, y - 2 ) ); @@ -101,18 +81,37 @@ public class ContainerFormationPlane extends ContainerUpgradeable this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.invPlayer ) ).setNotDraggable() ); } + @Override + protected boolean supportCapacity() + { + return true; + } + + @Override + public int availableUpgrades() + { + return 5; + } + @Override public void detectAndSendChanges() { this.verifyPermissions( SecurityPermissions.BUILD, false ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { - this.fzMode = ( FuzzyMode ) this.upgradeable.getConfigManager().getSetting( Settings.FUZZY_MODE ); - this.placeMode = ( YesNo ) this.upgradeable.getConfigManager().getSetting( Settings.PLACE_BLOCK ); + this.fzMode = (FuzzyMode) this.upgradeable.getConfigManager().getSetting( Settings.FUZZY_MODE ); + this.placeMode = (YesNo) this.upgradeable.getConfigManager().getSetting( Settings.PLACE_BLOCK ); } this.standardDetectAndSendChanges(); } + @Override + public boolean isSlotEnabled( int idx ) + { + int upgrades = this.upgradeable.getInstalledUpgrades( Upgrades.CAPACITY ); + + return upgrades > idx; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerGrinder.java b/src/main/java/appeng/container/implementations/ContainerGrinder.java index d134c0842..b187746c1 100644 --- a/src/main/java/appeng/container/implementations/ContainerGrinder.java +++ b/src/main/java/appeng/container/implementations/ContainerGrinder.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.container.AEBaseContainer; @@ -26,12 +27,14 @@ import appeng.container.slot.SlotOutput; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.grindstone.TileGrinder; + public class ContainerGrinder extends AEBaseContainer { final TileGrinder grinder; - public ContainerGrinder(InventoryPlayer ip, TileGrinder grinder) { + public ContainerGrinder( InventoryPlayer ip, TileGrinder grinder ) + { super( ip, grinder, null ); this.grinder = grinder; @@ -47,5 +50,4 @@ public class ContainerGrinder extends AEBaseContainer this.bindPlayerInventory( ip, 0, 176 - /* height of player inventory */82 ); } - } diff --git a/src/main/java/appeng/container/implementations/ContainerIOPort.java b/src/main/java/appeng/container/implementations/ContainerIOPort.java index 78b6f0ee4..ad90b8d0e 100644 --- a/src/main/java/appeng/container/implementations/ContainerIOPort.java +++ b/src/main/java/appeng/container/implementations/ContainerIOPort.java @@ -50,6 +50,12 @@ public class ContainerIOPort extends ContainerUpgradeable this.ioPort = te; } + @Override + protected int getHeight() + { + return 166; + } + @Override protected void setupConfig() { @@ -58,14 +64,14 @@ public class ContainerIOPort extends ContainerUpgradeable IInventory cells = this.upgradeable.getInventoryByName( "cells" ); - for ( int y = 0; y < 3; y++ ) - for ( int x = 0; x < 2; x++ ) + for( int y = 0; y < 3; y++ ) + for( int x = 0; x < 2; x++ ) this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, cells, x + y * 2, offX + x * 18, offY + y * 18, this.invPlayer ) ); offX = 122; offY = 17; - for ( int y = 0; y < 3; y++ ) - for ( int x = 0; x < 2; x++ ) + for( int y = 0; y < 3; y++ ) + for( int x = 0; x < 2; x++ ) this.addSlotToContainer( new SlotOutput( cells, 6 + x + y * 2, offX + x * 18, offY + y * 18, SlotRestrictedInput.PlacableItemType.STORAGE_CELLS.IIcon ) ); IInventory upgrades = this.upgradeable.getInventoryByName( "upgrades" ); @@ -75,9 +81,9 @@ public class ContainerIOPort extends ContainerUpgradeable } @Override - protected int getHeight() + protected boolean supportCapacity() { - return 166; + return false; } @Override @@ -86,18 +92,12 @@ public class ContainerIOPort extends ContainerUpgradeable return 3; } - @Override - protected boolean supportCapacity() - { - return false; - } - @Override public void detectAndSendChanges() { this.verifyPermissions( SecurityPermissions.BUILD, false ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { this.opMode = (OperationMode) this.upgradeable.getConfigManager().getSetting( Settings.OPERATION_MODE ); this.fMode = (FullnessMode) this.upgradeable.getConfigManager().getSetting( Settings.FULLNESS_MODE ); diff --git a/src/main/java/appeng/container/implementations/ContainerInscriber.java b/src/main/java/appeng/container/implementations/ContainerInscriber.java index d81c1c67a..6870e219c 100644 --- a/src/main/java/appeng/container/implementations/ContainerInscriber.java +++ b/src/main/java/appeng/container/implementations/ContainerInscriber.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; @@ -33,6 +34,7 @@ import appeng.recipes.handlers.Inscribe.InscriberRecipe; import appeng.tile.misc.TileInscriber; import appeng.util.Platform; + public class ContainerInscriber extends ContainerUpgradeable implements IProgressProvider { @@ -42,13 +44,13 @@ public class ContainerInscriber extends ContainerUpgradeable implements IProgres final Slot middle; final Slot bottom; - @GuiSync(2) + @GuiSync( 2 ) public int maxProcessingTime = -1; - @GuiSync(3) + @GuiSync( 3 ) public int processingTime = -1; - public ContainerInscriber(InventoryPlayer ip, TileInscriber te) + public ContainerInscriber( InventoryPlayer ip, TileInscriber te ) { super( ip, te ); this.ti = te; @@ -60,7 +62,6 @@ public class ContainerInscriber extends ContainerUpgradeable implements IProgres this.addSlotToContainer( new SlotOutput( this.ti, 3, 113, 40, -1 ) ); this.bindPlayerInventory( ip, 0, this.getHeight() - /* height of player inventory */82 ); - } @Override @@ -70,9 +71,11 @@ public class ContainerInscriber extends ContainerUpgradeable implements IProgres } @Override - public int availableUpgrades() + /** + * Overridden super.setupConfig to prevent setting up the fake slots + */ protected void setupConfig() { - return 3; + this.setupUpgrades(); } @Override @@ -82,92 +85,9 @@ public class ContainerInscriber extends ContainerUpgradeable implements IProgres } @Override - /** - * Overridden super.setupConfig to prevent setting up the fake slots - */ - protected void setupConfig() + public int availableUpgrades() { - this.setupUpgrades(); - } - - @Override - public boolean isValidForSlot(Slot s, ItemStack is) - { - ItemStack PlateA = this.ti.getStackInSlot( 0 ); - ItemStack PlateB = this.ti.getStackInSlot( 1 ); - - if ( s == this.middle ) - { - for (ItemStack i : Inscribe.PLATES ) - { - if ( Platform.isSameItemPrecise( i, is ) ) - return false; - } - - boolean matches = false; - boolean found = false; - - for (InscriberRecipe i : Inscribe.RECIPES ) - { - boolean matchA = (PlateA == null && i.plateA == null) || (Platform.isSameItemPrecise( PlateA, i.plateA )) && // and... - (PlateB == null && i.plateB == null) | (Platform.isSameItemPrecise( PlateB, i.plateB )); - - boolean matchB = (PlateB == null && i.plateA == null) || (Platform.isSameItemPrecise( PlateB, i.plateA )) && // and... - (PlateA == null && i.plateB == null) | (Platform.isSameItemPrecise( PlateA, i.plateB )); - - if ( matchA || matchB ) - { - matches = true; - for (ItemStack option : i.imprintable) - { - if ( Platform.isSameItemPrecise( is, option ) ) - found = true; - } - - } - } - - if ( matches && !found ) - return false; - } - - if ( (s == this.top && PlateB != null) || (s == this.bottom && PlateA != null) ) - { - boolean isValid = false; - ItemStack otherSlot = null; - if ( s == this.top ) - otherSlot = this.bottom.getStack(); - else - otherSlot = this.top.getStack(); - - // name presses - final IItemDefinition namePress = AEApi.instance().definitions().materials().namePress(); - if ( namePress.isSameAs( otherSlot ) ) - { - return namePress.isSameAs( is ); - } - - // everything else - for (InscriberRecipe i : Inscribe.RECIPES ) - { - if ( Platform.isSameItemPrecise( i.plateA, otherSlot ) ) - { - isValid = Platform.isSameItemPrecise( is, i.plateB ); - } - else if ( Platform.isSameItemPrecise( i.plateB, otherSlot ) ) - { - isValid = Platform.isSameItemPrecise( is, i.plateA ); - } - - if ( isValid ) - break; - } - - if ( !isValid ) - return false; - } - - return true; + return 3; } @Override @@ -175,13 +95,92 @@ public class ContainerInscriber extends ContainerUpgradeable implements IProgres { this.standardDetectAndSendChanges(); - if ( Platform.isServer() ) + if( Platform.isServer() ) { this.maxProcessingTime = this.ti.maxProcessingTime; this.processingTime = this.ti.processingTime; } } + @Override + public boolean isValidForSlot( Slot s, ItemStack is ) + { + ItemStack PlateA = this.ti.getStackInSlot( 0 ); + ItemStack PlateB = this.ti.getStackInSlot( 1 ); + + if( s == this.middle ) + { + for( ItemStack i : Inscribe.PLATES ) + { + if( Platform.isSameItemPrecise( i, is ) ) + return false; + } + + boolean matches = false; + boolean found = false; + + for( InscriberRecipe i : Inscribe.RECIPES ) + { + boolean matchA = ( PlateA == null && i.plateA == null ) || ( Platform.isSameItemPrecise( PlateA, i.plateA ) ) && // and... + ( PlateB == null && i.plateB == null ) | ( Platform.isSameItemPrecise( PlateB, i.plateB ) ); + + boolean matchB = ( PlateB == null && i.plateA == null ) || ( Platform.isSameItemPrecise( PlateB, i.plateA ) ) && // and... + ( PlateA == null && i.plateB == null ) | ( Platform.isSameItemPrecise( PlateA, i.plateB ) ); + + if( matchA || matchB ) + { + matches = true; + for( ItemStack option : i.imprintable ) + { + if( Platform.isSameItemPrecise( is, option ) ) + found = true; + } + } + } + + if( matches && !found ) + return false; + } + + if( ( s == this.top && PlateB != null ) || ( s == this.bottom && PlateA != null ) ) + { + boolean isValid = false; + ItemStack otherSlot = null; + if( s == this.top ) + otherSlot = this.bottom.getStack(); + else + otherSlot = this.top.getStack(); + + // name presses + final IItemDefinition namePress = AEApi.instance().definitions().materials().namePress(); + if( namePress.isSameAs( otherSlot ) ) + { + return namePress.isSameAs( is ); + } + + // everything else + for( InscriberRecipe i : Inscribe.RECIPES ) + { + if( Platform.isSameItemPrecise( i.plateA, otherSlot ) ) + { + isValid = Platform.isSameItemPrecise( is, i.plateB ); + } + else if( Platform.isSameItemPrecise( i.plateB, otherSlot ) ) + { + isValid = Platform.isSameItemPrecise( is, i.plateA ); + } + + if( isValid ) + break; + } + + if( !isValid ) + return false; + } + + return true; + } + @Override public int getCurrentProgress() { diff --git a/src/main/java/appeng/container/implementations/ContainerInterface.java b/src/main/java/appeng/container/implementations/ContainerInterface.java index e5f5f27b2..71c05f47b 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterface.java +++ b/src/main/java/appeng/container/implementations/ContainerInterface.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.api.config.SecurityPermissions; @@ -31,31 +32,32 @@ import appeng.container.slot.SlotRestrictedInput; import appeng.helpers.DualityInterface; import appeng.helpers.IInterfaceHost; + public class ContainerInterface extends ContainerUpgradeable { final DualityInterface myDuality; - @GuiSync(3) + @GuiSync( 3 ) public YesNo bMode = YesNo.NO; - @GuiSync(4) + @GuiSync( 4 ) public YesNo iTermMode = YesNo.YES; - public ContainerInterface(InventoryPlayer ip, IInterfaceHost te) { + public ContainerInterface( InventoryPlayer ip, IInterfaceHost te ) + { super( ip, te.getInterfaceDuality().getHost() ); this.myDuality = te.getInterfaceDuality(); - for (int x = 0; x < 9; x++) + for( int x = 0; x < 9; x++ ) this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality.getPatterns(), x, 8 + 18 * x, 90 + 7, this.invPlayer ) ); - for (int x = 0; x < 8; x++) + for( int x = 0; x < 8; x++ ) this.addSlotToContainer( new SlotFake( this.myDuality.getConfig(), x, 17 + 18 * x, 35 ) ); - for (int x = 0; x < 8; x++) + for( int x = 0; x < 8; x++ ) this.addSlotToContainer( new SlotNormal( this.myDuality.getStorage(), x, 17 + 18 * x, 35 + 18 ) ); - } @Override @@ -70,13 +72,6 @@ public class ContainerInterface extends ContainerUpgradeable this.setupUpgrades(); } - @Override - protected void loadSettingsFromHost(IConfigManager cm) - { - this.bMode = (YesNo) cm.getSetting( Settings.BLOCK ); - this.iTermMode = (YesNo) cm.getSetting( Settings.INTERFACE_TERMINAL ); - } - @Override public int availableUpgrades() { @@ -89,4 +84,11 @@ public class ContainerInterface extends ContainerUpgradeable this.verifyPermissions( SecurityPermissions.BUILD, false ); super.detectAndSendChanges(); } + + @Override + protected void loadSettingsFromHost( IConfigManager cm ) + { + this.bMode = (YesNo) cm.getSetting( Settings.BLOCK ); + this.iTermMode = (YesNo) cm.getSetting( Settings.INTERFACE_TERMINAL ); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java b/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java index 9b2ad20c2..9e0da207d 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java +++ b/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java @@ -53,6 +53,7 @@ import appeng.util.inv.AdaptorIInventory; import appeng.util.inv.AdaptorPlayerHand; import appeng.util.inv.WrapperInvSlot; + public class ContainerInterfaceTerminal extends AEBaseContainer { @@ -61,61 +62,124 @@ public class ContainerInterfaceTerminal extends AEBaseContainer */ static private long autoBase = Long.MIN_VALUE; - - static class InvTracker - { - - final long which = autoBase++; - final String unlocalizedName; - - public InvTracker(DualityInterface dual, IInventory patterns, String unlocalizedName) { - this.server = patterns; - this.client = new AppEngInternalInventory( null, this.server.getSizeInventory() ); - this.unlocalizedName = unlocalizedName; - this.sortBy = dual.getSortValue(); - } - - final IInventory client; - final IInventory server; - public final long sortBy; - - } - final Map diList = new HashMap(); final Map byId = new HashMap(); IGrid g; + NBTTagCompound data = new NBTTagCompound(); - public ContainerInterfaceTerminal(InventoryPlayer ip, PartMonitor anchor) { + public ContainerInterfaceTerminal( InventoryPlayer ip, PartMonitor anchor ) + { super( ip, anchor ); - if ( Platform.isServer() ) + if( Platform.isServer() ) this.g = anchor.getActionableNode().getGrid(); this.bindPlayerInventory( ip, 0, 222 - /* height of player inventory */82 ); } - NBTTagCompound data = new NBTTagCompound(); - - static class PatternInvSlot extends WrapperInvSlot + @Override + public void detectAndSendChanges() { + if( Platform.isClient() ) + return; - public PatternInvSlot(IInventory inv) { - super( inv ); - } + super.detectAndSendChanges(); - @Override - public boolean isItemValid(ItemStack itemstack) + if( this.g == null ) + return; + + int total = 0; + boolean missing = false; + + IActionHost host = this.getActionHost(); + if( host != null ) { - return itemstack != null && itemstack.getItem() instanceof ItemEncodedPattern; + IGridNode agn = host.getActionableNode(); + if( agn != null && agn.isActive() ) + { + for( IGridNode gn : this.g.getMachines( TileInterface.class ) ) + { + if( gn.isActive() ) + { + IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) + continue; + + InvTracker t = this.diList.get( ih ); + + if( t == null ) + missing = true; + else + { + DualityInterface dual = ih.getInterfaceDuality(); + if( !t.unlocalizedName.equals( dual.getTermName() ) ) + missing = true; + } + + total++; + } + } + + for( IGridNode gn : this.g.getMachines( PartInterface.class ) ) + { + if( gn.isActive() ) + { + IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) + continue; + + InvTracker t = this.diList.get( ih ); + + if( t == null ) + missing = true; + else + { + DualityInterface dual = ih.getInterfaceDuality(); + if( !t.unlocalizedName.equals( dual.getTermName() ) ) + missing = true; + } + + total++; + } + } + } } + if( total != this.diList.size() || missing ) + this.regenList( this.data ); + else + { + for( Entry en : this.diList.entrySet() ) + { + InvTracker inv = en.getValue(); + for( int x = 0; x < inv.server.getSizeInventory(); x++ ) + { + if( this.isDifferent( inv.server.getStackInSlot( x ), inv.client.getStackInSlot( x ) ) ) + this.addItems( this.data, inv, x, 1 ); + } + } + } + + if( !this.data.hasNoTags() ) + { + try + { + NetworkHandler.instance.sendTo( new PacketCompressedNBT( this.data ), (EntityPlayerMP) this.getPlayerInv().player ); + } + catch( IOException e ) + { + // :P + } + + this.data = new NBTTagCompound(); + } } @Override - public void doAction(EntityPlayerMP player, InventoryAction action, int slot, long id) + public void doAction( EntityPlayerMP player, InventoryAction action, int slot, long id ) { InvTracker inv = this.byId.get( id ); - if ( inv != null ) + if( inv != null ) { ItemStack is = inv.server.getStackInSlot( slot ); boolean hasItemInHand = player.inventory.getItemStack() != null; @@ -127,226 +191,117 @@ public class ContainerInterfaceTerminal extends AEBaseContainer IInventory theSlot = slotInv.getWrapper( slot ); InventoryAdaptor interfaceSlot = new AdaptorIInventory( theSlot ); - switch (action) + switch( action ) { - case PICKUP_OR_SET_DOWN: + case PICKUP_OR_SET_DOWN: - if ( hasItemInHand ) - { - ItemStack inSlot = theSlot.getStackInSlot( 0 ); - if ( inSlot == null ) - player.inventory.setItemStack( interfaceSlot.addItems( player.inventory.getItemStack() ) ); - else + if( hasItemInHand ) { - inSlot = inSlot.copy(); - ItemStack inHand = player.inventory.getItemStack().copy(); - - theSlot.setInventorySlotContents( 0, null ); - player.inventory.setItemStack( null ); - - player.inventory.setItemStack( interfaceSlot.addItems( inHand.copy() ) ); - - if ( player.inventory.getItemStack() == null ) - player.inventory.setItemStack( inSlot ); + ItemStack inSlot = theSlot.getStackInSlot( 0 ); + if( inSlot == null ) + player.inventory.setItemStack( interfaceSlot.addItems( player.inventory.getItemStack() ) ); else { - player.inventory.setItemStack( inHand ); - theSlot.setInventorySlotContents( 0, inSlot ); + inSlot = inSlot.copy(); + ItemStack inHand = player.inventory.getItemStack().copy(); + + theSlot.setInventorySlotContents( 0, null ); + player.inventory.setItemStack( null ); + + player.inventory.setItemStack( interfaceSlot.addItems( inHand.copy() ) ); + + if( player.inventory.getItemStack() == null ) + player.inventory.setItemStack( inSlot ); + else + { + player.inventory.setItemStack( inHand ); + theSlot.setInventorySlotContents( 0, inSlot ); + } } } - } - else - { + else + { + IInventory mySlot = slotInv.getWrapper( slot ); + mySlot.setInventorySlotContents( 0, playerHand.addItems( mySlot.getStackInSlot( 0 ) ) ); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + + if( hasItemInHand ) + { + ItemStack extra = playerHand.removeItems( 1, null, null ); + if( extra != null ) + extra = interfaceSlot.addItems( extra ); + if( extra != null ) + playerHand.addItems( extra ); + } + else if( is != null ) + { + ItemStack extra = interfaceSlot.removeItems( ( is.stackSize + 1 ) / 2, null, null ); + if( extra != null ) + extra = playerHand.addItems( extra ); + if( extra != null ) + interfaceSlot.addItems( extra ); + } + + break; + case SHIFT_CLICK: + IInventory mySlot = slotInv.getWrapper( slot ); - mySlot.setInventorySlotContents( 0, playerHand.addItems( mySlot.getStackInSlot( 0 ) ) ); - } + InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); + mySlot.setInventorySlotContents( 0, playerInv.addItems( mySlot.getStackInSlot( 0 ) ) ); - break; - case SPLIT_OR_PLACE_SINGLE: + break; + case MOVE_REGION: - if ( hasItemInHand ) - { - ItemStack extra = playerHand.removeItems( 1, null, null ); - if ( extra != null ) - extra = interfaceSlot.addItems( extra ); - if ( extra != null ) - playerHand.addItems( extra ); - } - else if ( is != null ) - { - ItemStack extra = interfaceSlot.removeItems( (is.stackSize + 1) / 2, null, null ); - if ( extra != null ) - extra = playerHand.addItems( extra ); - if ( extra != null ) - interfaceSlot.addItems( extra ); - } + InventoryAdaptor playerInvAd = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); + for( int x = 0; x < inv.server.getSizeInventory(); x++ ) + { + inv.server.setInventorySlotContents( x, playerInvAd.addItems( inv.server.getStackInSlot( x ) ) ); + } - break; - case SHIFT_CLICK: + break; + case CREATIVE_DUPLICATE: - IInventory mySlot = slotInv.getWrapper( slot ); - InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - mySlot.setInventorySlotContents( 0, playerInv.addItems( mySlot.getStackInSlot( 0 ) ) ); + if( player.capabilities.isCreativeMode && !hasItemInHand ) + { + player.inventory.setItemStack( is == null ? null : is.copy() ); + } - break; - case MOVE_REGION: - - InventoryAdaptor playerInvAd = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - for (int x = 0; x < inv.server.getSizeInventory(); x++) - { - inv.server.setInventorySlotContents( x, playerInvAd.addItems( inv.server.getStackInSlot( x ) ) ); - } - - break; - case CREATIVE_DUPLICATE: - - if ( player.capabilities.isCreativeMode && !hasItemInHand ) - { - player.inventory.setItemStack( is == null ? null : is.copy() ); - } - - break; - default: - return; + break; + default: + return; } this.updateHeld( player ); } } - @Override - public void detectAndSendChanges() - { - if ( Platform.isClient() ) - return; - - super.detectAndSendChanges(); - - if ( this.g == null ) - return; - - int total = 0; - boolean missing = false; - - IActionHost host = this.getActionHost(); - if ( host != null ) - { - IGridNode agn = host.getActionableNode(); - if ( agn != null && agn.isActive() ) - { - for (IGridNode gn : this.g.getMachines( TileInterface.class )) - { - if ( gn.isActive() ) - { - IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if ( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) - continue; - - InvTracker t = this.diList.get( ih ); - - if ( t == null ) - missing = true; - else - { - DualityInterface dual = ih.getInterfaceDuality(); - if ( !t.unlocalizedName.equals( dual.getTermName() ) ) - missing = true; - } - - total++; - } - } - - for (IGridNode gn : this.g.getMachines( PartInterface.class )) - { - if ( gn.isActive() ) - { - IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if ( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) - continue; - - InvTracker t = this.diList.get( ih ); - - if ( t == null ) - missing = true; - else - { - DualityInterface dual = ih.getInterfaceDuality(); - if ( !t.unlocalizedName.equals( dual.getTermName() ) ) - missing = true; - } - - total++; - } - } - } - } - - if ( total != this.diList.size() || missing ) - this.regenList( this.data ); - else - { - for (Entry en : this.diList.entrySet()) - { - InvTracker inv = en.getValue(); - for (int x = 0; x < inv.server.getSizeInventory(); x++) - { - if ( this.isDifferent( inv.server.getStackInSlot( x ), inv.client.getStackInSlot( x ) ) ) - this.addItems( this.data, inv, x, 1 ); - } - } - } - - if ( !this.data.hasNoTags() ) - { - try - { - NetworkHandler.instance.sendTo( new PacketCompressedNBT( this.data ), (EntityPlayerMP) this.getPlayerInv().player ); - } - catch (IOException e) - { - // :P - } - - this.data = new NBTTagCompound(); - } - } - - private boolean isDifferent(ItemStack a, ItemStack b) - { - if ( a == null && b == null ) - return false; - - if ( a == null || b == null ) - return true; - - return !ItemStack.areItemStacksEqual( a, b ); - } - - private void regenList(NBTTagCompound data) + private void regenList( NBTTagCompound data ) { this.byId.clear(); this.diList.clear(); IActionHost host = this.getActionHost(); - if ( host != null ) + if( host != null ) { IGridNode agn = host.getActionableNode(); - if ( agn != null && agn.isActive() ) + if( agn != null && agn.isActive() ) { - for (IGridNode gn : this.g.getMachines( TileInterface.class )) + for( IGridNode gn : this.g.getMachines( TileInterface.class ) ) { IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); DualityInterface dual = ih.getInterfaceDuality(); - if ( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) + if( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) this.diList.put( ih, new InvTracker( dual, dual.getPatterns(), dual.getTermName() ) ); } - for (IGridNode gn : this.g.getMachines( PartInterface.class )) + for( IGridNode gn : this.g.getMachines( PartInterface.class ) ) { IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); DualityInterface dual = ih.getInterfaceDuality(); - if ( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) + if( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) this.diList.put( ih, new InvTracker( dual, dual.getPatterns(), dual.getTermName() ) ); } } @@ -354,7 +309,7 @@ public class ContainerInterfaceTerminal extends AEBaseContainer data.setBoolean( "clear", true ); - for (Entry en : this.diList.entrySet()) + for( Entry en : this.diList.entrySet() ) { InvTracker inv = en.getValue(); this.byId.put( inv.which, inv ); @@ -362,18 +317,29 @@ public class ContainerInterfaceTerminal extends AEBaseContainer } } - private void addItems(NBTTagCompound data, InvTracker inv, int offset, int length) + private boolean isDifferent( ItemStack a, ItemStack b ) + { + if( a == null && b == null ) + return false; + + if( a == null || b == null ) + return true; + + return !ItemStack.areItemStacksEqual( a, b ); + } + + private void addItems( NBTTagCompound data, InvTracker inv, int offset, int length ) { String name = '=' + Long.toString( inv.which, Character.MAX_RADIX ); NBTTagCompound tag = data.getCompoundTag( name ); - if ( tag.hasNoTags() ) + if( tag.hasNoTags() ) { tag.setLong( "sortBy", inv.sortBy ); tag.setString( "un", inv.unlocalizedName ); } - for (int x = 0; x < length; x++) + for( int x = 0; x < length; x++ ) { NBTTagCompound itemNBT = new NBTTagCompound(); @@ -382,7 +348,7 @@ public class ContainerInterfaceTerminal extends AEBaseContainer // "update" client side. inv.client.setInventorySlotContents( x + offset, is == null ? null : is.copy() ); - if ( is != null ) + if( is != null ) is.writeToNBT( itemNBT ); tag.setTag( Integer.toString( x + offset ), itemNBT ); @@ -390,4 +356,38 @@ public class ContainerInterfaceTerminal extends AEBaseContainer data.setTag( name, tag ); } + + static class InvTracker + { + + public final long sortBy; + final long which = autoBase++; + final String unlocalizedName; + final IInventory client; + final IInventory server; + + public InvTracker( DualityInterface dual, IInventory patterns, String unlocalizedName ) + { + this.server = patterns; + this.client = new AppEngInternalInventory( null, this.server.getSizeInventory() ); + this.unlocalizedName = unlocalizedName; + this.sortBy = dual.getSortValue(); + } + } + + + static class PatternInvSlot extends WrapperInvSlot + { + + public PatternInvSlot( IInventory inv ) + { + super( inv ); + } + + @Override + public boolean isItemValid( ItemStack itemstack ) + { + return itemstack != null && itemstack.getItem() instanceof ItemEncodedPattern; + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java b/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java index 79d89dbe8..5d24e2b81 100644 --- a/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java +++ b/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java @@ -39,40 +39,35 @@ import appeng.container.slot.SlotRestrictedInput; import appeng.parts.automation.PartLevelEmitter; import appeng.util.Platform; + public class ContainerLevelEmitter extends ContainerUpgradeable { final PartLevelEmitter lvlEmitter; - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public GuiTextField textField; + @GuiSync( 2 ) + public LevelType lvType; + @GuiSync( 3 ) + public long EmitterValue = -1; + @GuiSync( 4 ) + public YesNo cmType; - @SideOnly(Side.CLIENT) - public void setTextField(GuiTextField level) + public ContainerLevelEmitter( InventoryPlayer ip, PartLevelEmitter te ) + { + super( ip, te ); + this.lvlEmitter = te; + } + + @SideOnly( Side.CLIENT ) + public void setTextField( GuiTextField level ) { this.textField = level; this.textField.setText( String.valueOf( this.EmitterValue ) ); } - public ContainerLevelEmitter(InventoryPlayer ip, PartLevelEmitter te) { - super( ip, te ); - this.lvlEmitter = te; - } - - @Override - public int availableUpgrades() - { - - return 1; - } - - @Override - protected boolean supportCapacity() - { - return false; - } - - public void setLevel(long l, EntityPlayer player) + public void setLevel( long l, EntityPlayer player ) { this.lvlEmitter.setReportingValue( l ); this.EmitterValue = l; @@ -85,34 +80,38 @@ public class ContainerLevelEmitter extends ContainerUpgradeable int y = 40; IInventory upgrades = this.upgradeable.getInventoryByName( "upgrades" ); - if ( this.availableUpgrades() > 0 ) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.invPlayer )).setNotDraggable() ); - if ( this.availableUpgrades() > 1 ) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.invPlayer )).setNotDraggable() ); - if ( this.availableUpgrades() > 2 ) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.invPlayer )).setNotDraggable() ); - if ( this.availableUpgrades() > 3 ) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.invPlayer )).setNotDraggable() ); + if( this.availableUpgrades() > 0 ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.invPlayer ) ).setNotDraggable() ); + if( this.availableUpgrades() > 1 ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.invPlayer ) ).setNotDraggable() ); + if( this.availableUpgrades() > 2 ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.invPlayer ) ).setNotDraggable() ); + if( this.availableUpgrades() > 3 ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.invPlayer ) ).setNotDraggable() ); IInventory inv = this.upgradeable.getInventoryByName( "config" ); this.addSlotToContainer( new SlotFakeTypeOnly( inv, 0, x, y ) ); } - @GuiSync(2) - public LevelType lvType; + @Override + protected boolean supportCapacity() + { + return false; + } - @GuiSync(3) - public long EmitterValue = -1; + @Override + public int availableUpgrades() + { - @GuiSync(4) - public YesNo cmType; + return 1; + } @Override public void detectAndSendChanges() { this.verifyPermissions( SecurityPermissions.BUILD, false ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { this.EmitterValue = this.lvlEmitter.getReportingValue(); this.cmType = (YesNo) this.upgradeable.getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ); @@ -125,13 +124,12 @@ public class ContainerLevelEmitter extends ContainerUpgradeable } @Override - public void onUpdate(String field, Object oldValue, Object newValue) + public void onUpdate( String field, Object oldValue, Object newValue ) { - if ( field.equals( "EmitterValue" ) ) + if( field.equals( "EmitterValue" ) ) { - if ( this.textField != null ) + if( this.textField != null ) this.textField.setText( String.valueOf( this.EmitterValue ) ); } } - } diff --git a/src/main/java/appeng/container/implementations/ContainerMAC.java b/src/main/java/appeng/container/implementations/ContainerMAC.java index 75361540d..1c18c5870 100644 --- a/src/main/java/appeng/container/implementations/ContainerMAC.java +++ b/src/main/java/appeng/container/implementations/ContainerMAC.java @@ -37,22 +37,39 @@ import appeng.items.misc.ItemEncodedPattern; import appeng.tile.crafting.TileMolecularAssembler; import appeng.util.Platform; + public class ContainerMAC extends ContainerUpgradeable implements IProgressProvider { - final TileMolecularAssembler tma; private static final int MAX_CRAFT_PROGRESS = 100; + final TileMolecularAssembler tma; + @GuiSync( 4 ) + public int craftProgress = 0; - public ContainerMAC(InventoryPlayer ip, TileMolecularAssembler te) + public ContainerMAC( InventoryPlayer ip, TileMolecularAssembler te ) { super( ip, te ); this.tma = te; } - @Override - public int availableUpgrades() + public boolean isValidItemForSlot( int slotIndex, ItemStack i ) { - return 5; + IInventory mac = this.upgradeable.getInventoryByName( "mac" ); + + ItemStack is = mac.getStackInSlot( 10 ); + if( is == null ) + return false; + + if( is.getItem() instanceof ItemEncodedPattern ) + { + World w = this.getTileEntity().getWorldObj(); + ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); + if( ph.isCraftable() ) + return ph.isValidItemForSlot( slotIndex, i, w ); + } + + return false; } @Override @@ -61,35 +78,6 @@ public class ContainerMAC extends ContainerUpgradeable implements IProgressProvi return 197; } - @Override - protected boolean supportCapacity() - { - return false; - } - - @GuiSync(4) - public int craftProgress = 0; - - public boolean isValidItemForSlot(int slotIndex, ItemStack i) - { - IInventory mac = this.upgradeable.getInventoryByName( "mac" ); - - ItemStack is = mac.getStackInSlot( 10 ); - if ( is == null ) - return false; - - if ( is.getItem() instanceof ItemEncodedPattern ) - { - World w = this.getTileEntity().getWorldObj(); - ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); - if ( ph.isCraftable() ) - return ph.isValidItemForSlot( slotIndex, i, w ); - } - - return false; - } - @Override protected void setupConfig() { @@ -98,8 +86,8 @@ public class ContainerMAC extends ContainerUpgradeable implements IProgressProvi IInventory mac = this.upgradeable.getInventoryByName( "mac" ); - for (int y = 0; y < 3; y++) - for (int x = 0; x < 3; x++) + for( int y = 0; y < 3; y++ ) + for( int x = 0; x < 3; x++ ) { SlotMACPattern s = new SlotMACPattern( this, mac, x + y * 3, offX + x * 18, offY + y * 18 ); this.addSlotToContainer( s ); @@ -115,16 +103,23 @@ public class ContainerMAC extends ContainerUpgradeable implements IProgressProvi offY = 17; IInventory upgrades = this.upgradeable.getInventoryByName( "upgrades" ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.invPlayer )) - .setNotDraggable() ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.invPlayer )) - .setNotDraggable() ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.invPlayer )) - .setNotDraggable() ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.invPlayer )) - .setNotDraggable() ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.invPlayer )) - .setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.invPlayer ) ).setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.invPlayer ) ).setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.invPlayer ) ).setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.invPlayer ) ).setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.invPlayer ) ).setNotDraggable() ); + } + + @Override + protected boolean supportCapacity() + { + return false; + } + + @Override + public int availableUpgrades() + { + return 5; } @Override @@ -132,7 +127,7 @@ public class ContainerMAC extends ContainerUpgradeable implements IProgressProvi { this.verifyPermissions( SecurityPermissions.BUILD, false ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { this.rsMode = (RedstoneMode) this.upgradeable.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); } @@ -153,5 +148,4 @@ public class ContainerMAC extends ContainerUpgradeable implements IProgressProvi { return MAX_CRAFT_PROGRESS; } - } diff --git a/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java b/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java index 4ef799e17..63f7d1402 100644 --- a/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java +++ b/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import java.io.IOException; import java.nio.BufferOverflowException; @@ -66,33 +67,30 @@ import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; + public class ContainerMEMonitorable extends AEBaseContainer implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver { + public final SlotRestrictedInput[] cellView = new SlotRestrictedInput[5]; final IMEMonitor monitor; final IItemList items = AEApi.instance().storage().createItemList(); - - IConfigManager serverCM; final IConfigManager clientCM; - - @GuiSync(99) - public boolean canAccessViewCells = false; - - @GuiSync(98) - public boolean hasPower = false; - - public final SlotRestrictedInput[] cellView = new SlotRestrictedInput[5]; - - public IConfigManagerHost gui; - private IGridNode networkNode; private final ITerminalHost host; + @GuiSync( 99 ) + public boolean canAccessViewCells = false; + @GuiSync( 98 ) + public boolean hasPower = false; + public IConfigManagerHost gui; + IConfigManager serverCM; + private IGridNode networkNode; - public IGridNode getNetworkNode() + public ContainerMEMonitorable( InventoryPlayer ip, ITerminalHost monitorable ) { - return this.networkNode; + this( ip, monitorable, true ); } - protected ContainerMEMonitorable(InventoryPlayer ip, ITerminalHost monitorable, boolean bindInventory) { + protected ContainerMEMonitorable( InventoryPlayer ip, ITerminalHost monitorable, boolean bindInventory ) + { super( ip, monitorable instanceof TileEntity ? (TileEntity) monitorable : null, monitorable instanceof IPart ? (IPart) monitorable : null ); this.host = monitorable; @@ -102,29 +100,29 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa this.clientCM.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); this.clientCM.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { this.serverCM = monitorable.getConfigManager(); this.monitor = monitorable.getItemInventory(); - if ( this.monitor != null ) + if( this.monitor != null ) { this.monitor.addListener( this, null ); this.cellInv = this.monitor; - if ( monitorable instanceof IPortableCell ) + if( monitorable instanceof IPortableCell ) this.powerSrc = (IPortableCell) monitorable; - else if ( monitorable instanceof IMEChest ) + else if( monitorable instanceof IMEChest ) this.powerSrc = (IMEChest) monitorable; - else if ( monitorable instanceof IGridHost ) + else if( monitorable instanceof IGridHost ) { - IGridNode node = ((IGridHost) monitorable).getGridNode( ForgeDirection.UNKNOWN ); - if ( node != null ) + IGridNode node = ( (IGridHost) monitorable ).getGridNode( ForgeDirection.UNKNOWN ); + if( node != null ) { this.networkNode = node; IGrid g = node.getGrid(); - if ( g != null ) + if( g != null ) this.powerSrc = new ChannelPowerSrc( this.networkNode, (IEnergyGrid) g.getCache( IEnergyGrid.class ) ); } } @@ -136,48 +134,48 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa this.monitor = null; this.canAccessViewCells = false; - if ( monitorable instanceof IViewCellStorage ) + if( monitorable instanceof IViewCellStorage ) { - for (int y = 0; y < 5; y++) + for( int y = 0; y < 5; y++ ) { - this.cellView[y] = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.VIEW_CELL, ((IViewCellStorage) monitorable).getViewCellStorage(), y, 206, y * 18 + 8, - this.invPlayer ); + this.cellView[y] = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.VIEW_CELL, ( (IViewCellStorage) monitorable ).getViewCellStorage(), y, 206, y * 18 + 8, this.invPlayer ); this.cellView[y].allowEdit = this.canAccessViewCells; this.addSlotToContainer( this.cellView[y] ); } } - if ( bindInventory ) + if( bindInventory ) this.bindPlayerInventory( ip, 0, 0 ); } - public ContainerMEMonitorable(InventoryPlayer ip, ITerminalHost monitorable) { - this( ip, monitorable, true ); + public IGridNode getNetworkNode() + { + return this.networkNode; } @Override public void detectAndSendChanges() { - if ( Platform.isServer() ) + if( Platform.isServer() ) { - if ( this.monitor != this.host.getItemInventory() ) + if( this.monitor != this.host.getItemInventory() ) this.isContainerValid = false; - for (Settings set : this.serverCM.getSettings()) + for( Settings set : this.serverCM.getSettings() ) { Enum sideLocal = this.serverCM.getSetting( set ); Enum sideRemote = this.clientCM.getSetting( set ); - if ( sideLocal != sideRemote ) + if( sideLocal != sideRemote ) { this.clientCM.putSetting( set, sideLocal ); - for (Object crafter : this.crafters) + for( Object crafter : this.crafters ) { try { NetworkHandler.instance.sendTo( new PacketValueConfig( set.name(), sideLocal.name() ), (EntityPlayerMP) crafter ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } @@ -185,7 +183,7 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa } } - if ( !this.items.isEmpty() ) + if( !this.items.isEmpty() ) { try { @@ -193,10 +191,10 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - for (IAEItemStack is : this.items) + for( IAEItemStack is : this.items ) { IAEItemStack send = monitorCache.findPrecise( is ); - if ( send == null ) + if( send == null ) { is.setStackSize( 0 ); piu.appendItem( is ); @@ -205,18 +203,18 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa piu.appendItem( send ); } - if ( !piu.isEmpty() ) + if( !piu.isEmpty() ) { this.items.resetStatus(); - for (Object c : this.crafters) + for( Object c : this.crafters ) { - if ( c instanceof EntityPlayer ) + if( c instanceof EntityPlayer ) NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); } } } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } @@ -226,11 +224,11 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa boolean oldCanAccessViewCells = this.canAccessViewCells; this.canAccessViewCells = this.hasAccess( SecurityPermissions.BUILD, false ); - if ( this.canAccessViewCells != oldCanAccessViewCells ) + if( this.canAccessViewCells != oldCanAccessViewCells ) { - for (int y = 0; y < 5; y++) + for( int y = 0; y < 5; y++ ) { - if ( this.cellView[y] != null ) + if( this.cellView[y] != null ) this.cellView[y].allowEdit = this.canAccessViewCells; } } @@ -243,42 +241,55 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa { try { - if ( this.networkNode != null ) + if( this.networkNode != null ) this.hasPower = this.networkNode.isActive(); - else if ( this.powerSrc instanceof IEnergyGrid ) - this.hasPower = ((IEnergyGrid) this.powerSrc).isNetworkPowered(); + else if( this.powerSrc instanceof IEnergyGrid ) + this.hasPower = ( (IEnergyGrid) this.powerSrc ).isNetworkPowered(); else this.hasPower = this.powerSrc.extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.8; } - catch (Throwable t) + catch( Throwable t ) { // :P } } @Override - public void addCraftingToCrafters(ICrafting c) + public void onUpdate( String field, Object oldValue, Object newValue ) + { + if( field.equals( "canAccessViewCells" ) ) + { + for( int y = 0; y < 5; y++ ) + if( this.cellView[y] != null ) + this.cellView[y].allowEdit = this.canAccessViewCells; + } + + super.onUpdate( field, oldValue, newValue ); + } + + @Override + public void addCraftingToCrafters( ICrafting c ) { super.addCraftingToCrafters( c ); this.queueInventory( c ); } - public void queueInventory(ICrafting c) + public void queueInventory( ICrafting c ) { - if ( Platform.isServer() && c instanceof EntityPlayer && this.monitor != null ) + if( Platform.isServer() && c instanceof EntityPlayer && this.monitor != null ) { try { PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); IItemList monitorCache = this.monitor.getStorageList(); - for (IAEItemStack send : monitorCache) + for( IAEItemStack send : monitorCache ) { try { piu.appendItem( send ); } - catch (BufferOverflowException boe) + catch( BufferOverflowException boe ) { NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); @@ -289,20 +300,49 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } - } } + @Override + public void removeCraftingFromCrafters( ICrafting c ) + { + super.removeCraftingFromCrafters( c ); + + if( this.crafters.isEmpty() && this.monitor != null ) + this.monitor.removeListener( this ); + } + + @Override + public void onContainerClosed( EntityPlayer player ) + { + super.onContainerClosed( player ); + if( this.monitor != null ) + this.monitor.removeListener( this ); + } + + @Override + public boolean isValid( Object verificationToken ) + { + return true; + } + + @Override + public void postChange( IBaseMonitor monitor, Iterable change, BaseActionSource source ) + { + for( IAEItemStack is : change ) + this.items.add( is ); + } + @Override public void onListUpdate() { - for (Object c : this.crafters) + for( Object c : this.crafters ) { - if ( c instanceof ICrafting ) + if( c instanceof ICrafting ) { ICrafting cr = (ICrafting) c; this.queueInventory( cr ); @@ -311,59 +351,16 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa } @Override - public void onUpdate(String field, Object oldValue, Object newValue) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { - if ( field.equals( "canAccessViewCells" ) ) - { - for (int y = 0; y < 5; y++) - if ( this.cellView[y] != null ) - this.cellView[y].allowEdit = this.canAccessViewCells; - } - - super.onUpdate( field, oldValue, newValue ); - } - - @Override - public void onContainerClosed(EntityPlayer player) - { - super.onContainerClosed( player ); - if ( this.monitor != null ) - this.monitor.removeListener( this ); - } - - @Override - public void removeCraftingFromCrafters(ICrafting c) - { - super.removeCraftingFromCrafters( c ); - - if ( this.crafters.isEmpty() && this.monitor != null ) - this.monitor.removeListener( this ); - } - - @Override - public void postChange(IBaseMonitor monitor, Iterable change, BaseActionSource source) - { - for (IAEItemStack is : change) - this.items.add( is ); - } - - @Override - public boolean isValid(Object verificationToken) - { - return true; - } - - @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) - { - if ( this.gui != null ) + if( this.gui != null ) this.gui.updateSetting( manager, settingName, newValue ); } @Override public IConfigManager getConfigManager() { - if ( Platform.isServer() ) + if( Platform.isServer() ) return this.serverCM; return this.clientCM; } @@ -372,7 +369,7 @@ public class ContainerMEMonitorable extends AEBaseContainer implements IConfigMa { ItemStack[] list = new ItemStack[this.cellView.length]; - for (int x = 0; x < this.cellView.length; x++) + for( int x = 0; x < this.cellView.length; x++ ) list[x] = this.cellView[x].getStack(); return list; diff --git a/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java b/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java index 8287b2933..b5448d60c 100644 --- a/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java +++ b/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; @@ -26,33 +27,34 @@ import appeng.api.config.PowerMultiplier; import appeng.api.implementations.guiobjects.IPortableCell; import appeng.util.Platform; + public class ContainerMEPortableCell extends ContainerMEMonitorable { - double powerMultiplier = 0.5; final IPortableCell civ; + double powerMultiplier = 0.5; + int ticks = 0; - public ContainerMEPortableCell(InventoryPlayer ip, IPortableCell monitorable) { + public ContainerMEPortableCell( InventoryPlayer ip, IPortableCell monitorable ) + { super( ip, monitorable, false ); this.lockPlayerInventorySlot( ip.currentItem ); this.civ = monitorable; this.bindPlayerInventory( ip, 0, 0 ); } - int ticks = 0; - @Override public void detectAndSendChanges() { ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - if ( this.civ != null ) + if( this.civ != null ) { - if ( currentItem != this.civ.getItemStack() ) + if( currentItem != this.civ.getItemStack() ) { - if ( currentItem != null ) + if( currentItem != null ) { - if ( Platform.isSameItem( this.civ.getItemStack(), currentItem ) ) + if( Platform.isSameItem( this.civ.getItemStack(), currentItem ) ) this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.civ.getItemStack() ); else this.isContainerValid = false; @@ -66,7 +68,7 @@ public class ContainerMEPortableCell extends ContainerMEMonitorable // drain 1 ae t this.ticks++; - if ( this.ticks > 10 ) + if( this.ticks > 10 ) { this.civ.extractAEPower( this.powerMultiplier * this.ticks, Actionable.MODULATE, PowerMultiplier.CONFIG ); this.ticks = 0; diff --git a/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java b/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java index b66a4465f..84bb9a0a8 100644 --- a/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java +++ b/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; @@ -42,62 +43,62 @@ import appeng.core.sync.packets.PacketMEInventoryUpdate; import appeng.util.Platform; import appeng.util.item.AEItemStack; + public class ContainerNetworkStatus extends AEBaseContainer { + @GuiSync( 0 ) + public long avgAddition; + @GuiSync( 1 ) + public long powerUsage; + @GuiSync( 2 ) + public long currentPower; + @GuiSync( 3 ) + public long maxPower; IGrid network; + int delay = 40; - public ContainerNetworkStatus(InventoryPlayer ip, INetworkTool te) { + public ContainerNetworkStatus( InventoryPlayer ip, INetworkTool te ) + { super( ip, null, null ); IGridHost host = te.getGridHost(); - if ( host != null ) + if( host != null ) { this.findNode( host, ForgeDirection.UNKNOWN ); - for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) this.findNode( host, d ); } - if ( this.network == null && Platform.isServer() ) + if( this.network == null && Platform.isServer() ) this.isContainerValid = false; } - private void findNode(IGridHost host, ForgeDirection d) + private void findNode( IGridHost host, ForgeDirection d ) { - if ( this.network == null ) + if( this.network == null ) { IGridNode node = host.getGridNode( d ); - if ( node != null ) + if( node != null ) this.network = node.getGrid(); } } - int delay = 40; - - @GuiSync(0) - public long avgAddition; - @GuiSync(1) - public long powerUsage; - @GuiSync(2) - public long currentPower; - @GuiSync(3) - public long maxPower; - @Override public void detectAndSendChanges() { this.delay++; - if ( Platform.isServer() && this.delay > 15 && this.network != null ) + if( Platform.isServer() && this.delay > 15 && this.network != null ) { this.delay = 0; IEnergyGrid eg = this.network.getCache( IEnergyGrid.class ); - if ( eg != null ) + if( eg != null ) { - this.avgAddition = (long) (100.0 * eg.getAvgPowerInjection()); - this.powerUsage = (long) (100.0 * eg.getAvgPowerUsage()); - this.currentPower = (long) (100.0 * eg.getStoredPower()); - this.maxPower = (long) (100.0 * eg.getMaxStoredPower()); + this.avgAddition = (long) ( 100.0 * eg.getAvgPowerInjection() ); + this.powerUsage = (long) ( 100.0 * eg.getAvgPowerUsage() ); + this.currentPower = (long) ( 100.0 * eg.getStoredPower() ); + this.maxPower = (long) ( 100.0 * eg.getMaxStoredPower() ); } PacketMEInventoryUpdate piu; @@ -105,37 +106,36 @@ public class ContainerNetworkStatus extends AEBaseContainer { piu = new PacketMEInventoryUpdate(); - for (Class machineClass : this.network.getMachinesClasses()) + for( Class machineClass : this.network.getMachinesClasses() ) { IItemList list = AEApi.instance().storage().createItemList(); - for (IGridNode machine : this.network.getMachines( machineClass )) + for( IGridNode machine : this.network.getMachines( machineClass ) ) { IGridBlock blk = machine.getGridBlock(); ItemStack is = blk.getMachineRepresentation(); - if ( is != null && is.getItem() != null ) + if( is != null && is.getItem() != null ) { IAEItemStack ais = AEItemStack.create( is ); ais.setStackSize( 1 ); - ais.setCountRequestable( (long) (blk.getIdlePowerUsage() * 100.0) ); + ais.setCountRequestable( (long) ( blk.getIdlePowerUsage() * 100.0 ) ); list.add( ais ); } } - for (IAEItemStack ais : list) + for( IAEItemStack ais : list ) piu.appendItem( ais ); } - for (Object c : this.crafters) + for( Object c : this.crafters ) { - if ( c instanceof EntityPlayer ) + if( c instanceof EntityPlayer ) NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); } } - catch (IOException e) + catch( IOException e ) { // :P } - } super.detectAndSendChanges(); } diff --git a/src/main/java/appeng/container/implementations/ContainerNetworkTool.java b/src/main/java/appeng/container/implementations/ContainerNetworkTool.java index 0195382be..381231974 100644 --- a/src/main/java/appeng/container/implementations/ContainerNetworkTool.java +++ b/src/main/java/appeng/container/implementations/ContainerNetworkTool.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -28,23 +29,25 @@ import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotRestrictedInput; import appeng.util.Platform; + public class ContainerNetworkTool extends AEBaseContainer { final INetworkTool toolInv; - @GuiSync(1) + @GuiSync( 1 ) public boolean facadeMode; - public ContainerNetworkTool(InventoryPlayer ip, INetworkTool te) { + public ContainerNetworkTool( InventoryPlayer ip, INetworkTool te ) + { super( ip, null, null ); this.toolInv = te; this.lockPlayerInventorySlot( ip.currentItem ); - for (int y = 0; y < 3; y++) - for (int x = 0; x < 3; x++) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, te, y * 3 + x, 80 - 18 + x * 18, 37 - 18 + y * 18, this.invPlayer )) ); + for( int y = 0; y < 3; y++ ) + for( int x = 0; x < 3; x++ ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, te, y * 3 + x, 80 - 18 + x * 18, 37 - 18 + y * 18, this.invPlayer ) ) ); this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); } @@ -61,11 +64,11 @@ public class ContainerNetworkTool extends AEBaseContainer { ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - if ( currentItem != this.toolInv.getItemStack() ) + if( currentItem != this.toolInv.getItemStack() ) { - if ( currentItem != null ) + if( currentItem != null ) { - if ( Platform.isSameItem( this.toolInv.getItemStack(), currentItem ) ) + if( Platform.isSameItem( this.toolInv.getItemStack(), currentItem ) ) { this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.toolInv.getItemStack() ); } @@ -76,7 +79,7 @@ public class ContainerNetworkTool extends AEBaseContainer this.isContainerValid = false; } - if ( this.isContainerValid ) + if( this.isContainerValid ) { NBTTagCompound data = Platform.openNbtData( currentItem ); this.facadeMode = data.getBoolean( "hideFacades" ); diff --git a/src/main/java/appeng/container/implementations/ContainerPatternTerm.java b/src/main/java/appeng/container/implementations/ContainerPatternTerm.java index 65edc0fe3..e6361a774 100644 --- a/src/main/java/appeng/container/implementations/ContainerPatternTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerPatternTerm.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import java.util.ArrayList; import java.util.List; @@ -65,23 +66,22 @@ import appeng.util.Platform; import appeng.util.inv.AdaptorPlayerHand; import appeng.util.item.AEItemStack; + public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket { + public final PartPatternTerminal ct; final AppEngInternalInventory cOut = new AppEngInternalInventory( null, 1 ); final IInventory crafting; - final SlotFakeCraftingMatrix[] craftingSlots = new SlotFakeCraftingMatrix[9]; final OptionalSlotFake[] outputSlots = new OptionalSlotFake[3]; - final SlotPatternTerm craftSlot; - final SlotRestrictedInput patternSlotIN; final SlotRestrictedInput patternSlotOUT; + @GuiSync( 97 ) + public boolean craftingMode = true; - public final PartPatternTerminal ct; - - public ContainerPatternTerm(InventoryPlayer ip, ITerminalHost monitorable) + public ContainerPatternTerm( InventoryPlayer ip, ITerminalHost monitorable ) { super( ip, monitorable, false ); this.ct = (PartPatternTerminal) monitorable; @@ -90,14 +90,14 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA IInventory output = this.ct.getInventoryByName( "output" ); this.crafting = this.ct.getInventoryByName( "crafting" ); - for (int y = 0; y < 3; y++) - for (int x = 0; x < 3; x++) + for( int y = 0; y < 3; y++ ) + for( int x = 0; x < 3; x++ ) this.addSlotToContainer( this.craftingSlots[x + y * 3] = new SlotFakeCraftingMatrix( this.crafting, x + y * 3, 18 + x * 18, -76 + y * 18 ) ); this.addSlotToContainer( this.craftSlot = new SlotPatternTerm( ip.player, this.mySrc, this.powerSrc, monitorable, this.crafting, patternInv, this.cOut, 110, -76 + 18, this, 2, this ) ); this.craftSlot.IIcon = -1; - for (int y = 0; y < 3; y++) + for( int y = 0; y < 3; y++ ) { this.addSlotToContainer( this.outputSlots[y] = new SlotPatternOutputs( output, this, y, 110, -76 + y * 18, 0, 0, 1 ) ); this.outputSlots[y].renderDisabled = false; @@ -115,31 +115,31 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA private void updateOrderOfOutputSlots() { - if ( !this.craftingMode ) + if( !this.craftingMode ) { this.craftSlot.xDisplayPosition = -9000; - for (int y = 0; y < 3; y++) + for( int y = 0; y < 3; y++ ) this.outputSlots[y].xDisplayPosition = this.outputSlots[y].defX; } else { this.craftSlot.xDisplayPosition = this.craftSlot.defX; - for (int y = 0; y < 3; y++) + for( int y = 0; y < 3; y++ ) this.outputSlots[y].xDisplayPosition = -9000; } } @Override - public void putStackInSlot(int par1, ItemStack par2ItemStack) + public void putStackInSlot( int par1, ItemStack par2ItemStack ) { super.putStackInSlot( par1, par2ItemStack ); this.getAndUpdateOutput(); } @Override - public void putStacksInSlots(ItemStack[] par1ArrayOfItemStack) + public void putStacksInSlots( ItemStack[] par1ArrayOfItemStack ) { super.putStacksInSlots( par1ArrayOfItemStack ); this.getAndUpdateOutput(); @@ -148,7 +148,7 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA public ItemStack getAndUpdateOutput() { InventoryCrafting ic = new InventoryCrafting( this, 3, 3 ); - for (int x = 0; x < ic.getSizeInventory(); x++) + for( int x = 0; x < ic.getSizeInventory(); x++ ) ic.setInventorySlotContents( x, this.crafting.getStackInSlot( x ) ); ItemStack is = CraftingManager.getInstance().findMatchingRecipe( ic, this.getPlayerInv().player.worldObj ); @@ -156,41 +156,18 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA return is; } - @GuiSync(97) - public boolean craftingMode = true; - - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - if ( Platform.isServer() ) - { - if ( this.craftingMode != this.ct.isCraftingRecipe() ) - { - this.craftingMode = this.ct.isCraftingRecipe(); - this.updateOrderOfOutputSlots(); - } - } - } - - @Override - public void onUpdate(String field, Object oldValue, Object newValue) - { - super.onUpdate( field, oldValue, newValue ); - - if ( field.equals( "craftingMode" ) ) - { - this.getAndUpdateOutput(); - this.updateOrderOfOutputSlots(); - } - } - @Override public void saveChanges() { } + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) + { + + } + public void encode() { ItemStack output = this.patternSlotOUT.getStack(); @@ -199,27 +176,27 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA ItemStack[] out = this.getOutputs(); // if there is no input, this would be silly. - if ( in == null || out == null ) + if( in == null || out == null ) return; // first check the output slots, should either be null, or a pattern - if ( output != null && !this.isPattern( output ) ) + if( output != null && !this.isPattern( output ) ) return; - // if nothing is there we should snag a new pattern. - else if ( output == null ) + // if nothing is there we should snag a new pattern. + else if( output == null ) { output = this.patternSlotIN.getStack(); - if ( output == null || !this.isPattern( output ) ) + if( output == null || !this.isPattern( output ) ) return; // no blanks. // remove one, and clear the input slot. output.stackSize--; - if ( output.stackSize == 0 ) + if( output.stackSize == 0 ) this.patternSlotIN.putStack( null ); // add a new encoded pattern. - for ( ItemStack encodedPatternStack : AEApi.instance().definitions().items().encodedPattern().maybeStack( 1 ).asSet() ) + for( ItemStack encodedPatternStack : AEApi.instance().definitions().items().encodedPattern().maybeStack( 1 ).asSet() ) { output = encodedPatternStack; this.patternSlotOUT.putStack( output ); @@ -232,10 +209,10 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA NBTTagList tagIn = new NBTTagList(); NBTTagList tagOut = new NBTTagList(); - for (ItemStack i : in) + for( ItemStack i : in ) tagIn.appendTag( this.createItemTag( i ) ); - for (ItemStack i : out) + for( ItemStack i : out ) tagOut.appendTag( this.createItemTag( i ) ); encodedValue.setTag( "in", tagIn ); @@ -245,29 +222,19 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA output.setTagCompound( encodedValue ); } - private NBTBase createItemTag(ItemStack i) - { - NBTTagCompound c = new NBTTagCompound(); - - if ( i != null ) - i.writeToNBT( c ); - - return c; - } - private ItemStack[] getInputs() { ItemStack[] input = new ItemStack[9]; boolean hasValue = false; - for (int x = 0; x < this.craftingSlots.length; x++) + for( int x = 0; x < this.craftingSlots.length; x++ ) { input[x] = this.craftingSlots[x].getStack(); - if ( input[x] != null ) + if( input[x] != null ) hasValue = true; } - if ( hasValue ) + if( hasValue ) return input; return null; @@ -275,10 +242,10 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA private ItemStack[] getOutputs() { - if ( this.craftingMode ) + if( this.craftingMode ) { ItemStack out = this.getAndUpdateOutput(); - if ( out != null && out.stackSize > 0 ) + if( out != null && out.stackSize > 0 ) return new ItemStack[] { out }; } else @@ -286,26 +253,26 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA List list = new ArrayList( 3 ); boolean hasValue = false; - for (OptionalSlotFake outputSlot : this.outputSlots) + for( OptionalSlotFake outputSlot : this.outputSlots ) { ItemStack out = outputSlot.getStack(); - if ( out != null && out.stackSize > 0 ) + if( out != null && out.stackSize > 0 ) { list.add( out ); hasValue = true; } } - if ( hasValue ) + if( hasValue ) return list.toArray( new ItemStack[list.size()] ); } return null; } - private boolean isPattern(ItemStack output) + private boolean isPattern( ItemStack output ) { - if ( output == null ) + if( output == null ) return false; final IDefinitions definitions = AEApi.instance().definitions(); @@ -316,44 +283,48 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA return isPattern; } - @Override - public boolean isSlotEnabled(int idx) + private NBTBase createItemTag( ItemStack i ) { - if ( idx == 1 ) + NBTTagCompound c = new NBTTagCompound(); + + if( i != null ) + i.writeToNBT( c ); + + return c; + } + + @Override + public boolean isSlotEnabled( int idx ) + { + if( idx == 1 ) return Platform.isServer() ? !this.ct.isCraftingRecipe() : !this.craftingMode; - else if ( idx == 2 ) + else if( idx == 2 ) return Platform.isServer() ? this.ct.isCraftingRecipe() : this.craftingMode; else return false; } - @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack) + public void craftOrGetItem( PacketPatternSlot packetPatternSlot ) { - - } - - public void craftOrGetItem(PacketPatternSlot packetPatternSlot) - { - if ( packetPatternSlot.slotItem != null && this.cellInv != null ) + if( packetPatternSlot.slotItem != null && this.cellInv != null ) { IAEItemStack out = packetPatternSlot.slotItem.copy(); InventoryAdaptor inv = new AdaptorPlayerHand( this.getPlayerInv().player ); InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( this.getPlayerInv().player, ForgeDirection.UNKNOWN ); - if ( packetPatternSlot.shift ) + if( packetPatternSlot.shift ) inv = playerInv; - if ( inv.simulateAdd( out.getItemStack() ) != null ) + if( inv.simulateAdd( out.getItemStack() ) != null ) return; IAEItemStack extracted = Platform.poweredExtraction( this.powerSrc, this.cellInv, out, this.mySrc ); EntityPlayer p = this.getPlayerInv().player; - if ( extracted != null ) + if( extracted != null ) { inv.addItems( extracted.getItemStack() ); - if ( p instanceof EntityPlayerMP ) + if( p instanceof EntityPlayerMP ) this.updateHeld( (EntityPlayerMP) p ); this.detectAndSendChanges(); return; @@ -361,14 +332,14 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); InventoryCrafting real = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for (int x = 0; x < 9; x++) + for( int x = 0; x < 9; x++ ) { ic.setInventorySlotContents( x, packetPatternSlot.pattern[x] == null ? null : packetPatternSlot.pattern[x].getItemStack() ); } IRecipe r = Platform.findMatchingRecipe( ic, p.worldObj ); - if ( r == null ) + if( r == null ) return; IMEMonitor storage = this.ct.getItemInventory(); @@ -376,68 +347,92 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA ItemStack is = r.getCraftingResult( ic ); - for (int x = 0; x < ic.getSizeInventory(); x++) + for( int x = 0; x < ic.getSizeInventory(); x++ ) { - if ( ic.getStackInSlot( x ) != null ) + if( ic.getStackInSlot( x ) != null ) { - ItemStack pulled = Platform.extractItemsByRecipe( this.powerSrc, this.mySrc, storage, p.worldObj, r, is, ic, ic.getStackInSlot( x ), x, all, - Actionable.MODULATE, ItemViewCell.createFilter( this.getViewCells() ) ); + ItemStack pulled = Platform.extractItemsByRecipe( this.powerSrc, this.mySrc, storage, p.worldObj, r, is, ic, ic.getStackInSlot( x ), x, all, Actionable.MODULATE, ItemViewCell.createFilter( this.getViewCells() ) ); real.setInventorySlotContents( x, pulled ); } } IRecipe rr = Platform.findMatchingRecipe( real, p.worldObj ); - if ( rr == r && Platform.isSameItemPrecise( rr.getCraftingResult( real ), is ) ) + if( rr == r && Platform.isSameItemPrecise( rr.getCraftingResult( real ), is ) ) { SlotCrafting sc = new SlotCrafting( p, real, this.cOut, 0, 0, 0 ); sc.onPickupFromSlot( p, is ); - for (int x = 0; x < real.getSizeInventory(); x++) + for( int x = 0; x < real.getSizeInventory(); x++ ) { ItemStack failed = playerInv.addItems( real.getStackInSlot( x ) ); - if ( failed != null ) + if( failed != null ) p.dropPlayerItemWithRandomChoice( failed, false ); } inv.addItems( is ); - if ( p instanceof EntityPlayerMP ) + if( p instanceof EntityPlayerMP ) this.updateHeld( (EntityPlayerMP) p ); this.detectAndSendChanges(); } else { - for (int x = 0; x < real.getSizeInventory(); x++) + for( int x = 0; x < real.getSizeInventory(); x++ ) { ItemStack failed = real.getStackInSlot( x ); - if ( failed != null ) + if( failed != null ) { this.cellInv.injectItems( AEItemStack.create( failed ), Actionable.MODULATE, new MachineSource( this.ct ) ); } } } - } } @Override - public void onSlotChange(Slot s) + public void detectAndSendChanges() { - if ( s == this.patternSlotOUT && Platform.isServer() ) + super.detectAndSendChanges(); + if( Platform.isServer() ) { - for (Object crafter : this.crafters) + if( this.craftingMode != this.ct.isCraftingRecipe() ) + { + this.craftingMode = this.ct.isCraftingRecipe(); + this.updateOrderOfOutputSlots(); + } + } + } + + @Override + public void onUpdate( String field, Object oldValue, Object newValue ) + { + super.onUpdate( field, oldValue, newValue ); + + if( field.equals( "craftingMode" ) ) + { + this.getAndUpdateOutput(); + this.updateOrderOfOutputSlots(); + } + } + + @Override + public void onSlotChange( Slot s ) + { + if( s == this.patternSlotOUT && Platform.isServer() ) + { + for( Object crafter : this.crafters ) { ICrafting icrafting = (ICrafting) crafter; - for (Object g : this.inventorySlots) + for( Object g : this.inventorySlots ) { - if ( g instanceof OptionalSlotFake || g instanceof SlotFakeCraftingMatrix ) + if( g instanceof OptionalSlotFake || g instanceof SlotFakeCraftingMatrix ) { Slot sri = (Slot) g; icrafting.sendSlotContents( this, sri.slotNumber, sri.getStack() ); } } - ((EntityPlayerMP) icrafting).isChangingQuantityOnly = false; + ( (EntityPlayerMP) icrafting ).isChangingQuantityOnly = false; } this.detectAndSendChanges(); } @@ -445,10 +440,10 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA public void clear() { - for (Slot s : this.craftingSlots) + for( Slot s : this.craftingSlots ) s.putStack( null ); - for (Slot s : this.outputSlots) + for( Slot s : this.outputSlots ) s.putStack( null ); this.detectAndSendChanges(); @@ -456,9 +451,9 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA } @Override - public IInventory getInventoryByName(String name) + public IInventory getInventoryByName( String name ) { - if (name.equals("player")) + if( name.equals( "player" ) ) { return this.invPlayer; } diff --git a/src/main/java/appeng/container/implementations/ContainerPriority.java b/src/main/java/appeng/container/implementations/ContainerPriority.java index 586f02e7c..ad45106c7 100644 --- a/src/main/java/appeng/container/implementations/ContainerPriority.java +++ b/src/main/java/appeng/container/implementations/ContainerPriority.java @@ -34,30 +34,31 @@ import appeng.container.guisync.GuiSync; import appeng.helpers.IPriorityHost; import appeng.util.Platform; + public class ContainerPriority extends AEBaseContainer { final IPriorityHost priHost; - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public GuiTextField textField; + @GuiSync( 2 ) + public long PriorityValue = -1; - @SideOnly(Side.CLIENT) - public void setTextField(GuiTextField level) + public ContainerPriority( InventoryPlayer ip, IPriorityHost te ) + { + super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); + this.priHost = te; + } + + @SideOnly( Side.CLIENT ) + public void setTextField( GuiTextField level ) { this.textField = level; this.textField.setText( String.valueOf( this.PriorityValue ) ); } - public ContainerPriority(InventoryPlayer ip, IPriorityHost te) { - super( ip, (TileEntity) (te instanceof TileEntity ? te : null), (IPart) (te instanceof IPart ? te : null) ); - this.priHost = te; - } - - @GuiSync(2) - public long PriorityValue = -1; - - public void setPriority(int newValue, EntityPlayer player) + public void setPriority( int newValue, EntityPlayer player ) { this.priHost.setPriority( newValue ); this.PriorityValue = newValue; @@ -69,18 +70,18 @@ public class ContainerPriority extends AEBaseContainer super.detectAndSendChanges(); this.verifyPermissions( SecurityPermissions.BUILD, false ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { this.PriorityValue = this.priHost.getPriority(); } } @Override - public void onUpdate(String field, Object oldValue, Object newValue) + public void onUpdate( String field, Object oldValue, Object newValue ) { - if ( field.equals( "PriorityValue" ) ) + if( field.equals( "PriorityValue" ) ) { - if ( this.textField != null ) + if( this.textField != null ) this.textField.setText( String.valueOf( this.PriorityValue ) ); } diff --git a/src/main/java/appeng/container/implementations/ContainerQNB.java b/src/main/java/appeng/container/implementations/ContainerQNB.java index 60674e2b9..25956d5d0 100644 --- a/src/main/java/appeng/container/implementations/ContainerQNB.java +++ b/src/main/java/appeng/container/implementations/ContainerQNB.java @@ -18,24 +18,26 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.qnb.TileQuantumBridge; + public class ContainerQNB extends AEBaseContainer { final TileQuantumBridge quantumBridge; - public ContainerQNB(InventoryPlayer ip, TileQuantumBridge quantumBridge) { + public ContainerQNB( InventoryPlayer ip, TileQuantumBridge quantumBridge ) + { super( ip, quantumBridge, null ); this.quantumBridge = quantumBridge; - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.QE_SINGULARITY, quantumBridge, 0, 80, 37, this.invPlayer )).setStackLimit( 1 ) ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.QE_SINGULARITY, quantumBridge, 0, 80, 37, this.invPlayer ) ).setStackLimit( 1 ) ); this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); } - } diff --git a/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java b/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java index cb29983f7..5ecae41d4 100644 --- a/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java +++ b/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; @@ -36,6 +37,7 @@ import appeng.tile.inventory.IAEAppEngInventory; import appeng.tile.inventory.InvOperation; import appeng.util.Platform; + public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngInventory, IInventory { @@ -46,12 +48,8 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn final QuartzKnifeOutput output; String myName = ""; - public void setName(String value) + public ContainerQuartzKnife( InventoryPlayer ip, QuartzKnifeObj te ) { - this.myName = value; - } - - public ContainerQuartzKnife(InventoryPlayer ip, QuartzKnifeObj te) { super( ip, null, null ); this.toolInv = te; @@ -63,16 +61,21 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn this.bindPlayerInventory( ip, 0, 184 - /* height of player inventory */82 ); } + public void setName( String value ) + { + this.myName = value; + } + @Override public void detectAndSendChanges() { ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - if ( currentItem != this.toolInv.getItemStack() ) + if( currentItem != this.toolInv.getItemStack() ) { - if ( currentItem != null ) + if( currentItem != null ) { - if ( Platform.isSameItem( this.toolInv.getItemStack(), currentItem ) ) + if( Platform.isSameItem( this.toolInv.getItemStack(), currentItem ) ) this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.toolInv.getItemStack() ); else this.isContainerValid = false; @@ -85,9 +88,9 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn } @Override - public void onContainerClosed(EntityPlayer par1EntityPlayer) + public void onContainerClosed( EntityPlayer par1EntityPlayer ) { - if ( this.inSlot.getStackInSlot( 0 ) != null ) + if( this.inSlot.getStackInSlot( 0 ) != null ) par1EntityPlayer.dropPlayerItemWithRandomChoice( this.inSlot.getStackInSlot( 0 ), false ); } @@ -98,7 +101,7 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) { } @@ -110,17 +113,17 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn } @Override - public ItemStack getStackInSlot(int var1) + public ItemStack getStackInSlot( int var1 ) { ItemStack input = this.inSlot.getStackInSlot( 0 ); - if ( input == null ) + if( input == null ) return null; - if ( SlotRestrictedInput.isMetalIngot( input ) ) + if( SlotRestrictedInput.isMetalIngot( input ) ) { - if ( this.myName.length() > 0 ) + if( this.myName.length() > 0 ) { - for ( ItemStack namePressStack : AEApi.instance().definitions().materials().namePress().maybeStack( 1 ).asSet() ) + for( ItemStack namePressStack : AEApi.instance().definitions().materials().namePress().maybeStack( 1 ).asSet() ) { final NBTTagCompound compound = Platform.openNbtData( namePressStack ); compound.setString( "InscribeName", this.myName ); @@ -134,12 +137,12 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn } @Override - public ItemStack decrStackSize(int var1, int var2) + public ItemStack decrStackSize( int var1, int var2 ) { ItemStack is = this.getStackInSlot( 0 ); - if ( is != null ) + if( is != null ) { - if ( this.makePlate() ) + if( this.makePlate() ) return is; } return null; @@ -147,12 +150,12 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn private boolean makePlate() { - if ( this.inSlot.decrStackSize( 0, 1 ) != null ) + if( this.inSlot.decrStackSize( 0, 1 ) != null ) { ItemStack item = this.toolInv.getItemStack(); item.damageItem( 1, this.getPlayerInv().player ); - if ( item.stackSize == 0 ) + if( item.stackSize == 0 ) { this.getPlayerInv().mainInventory[this.getPlayerInv().currentItem] = null; MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( this.getPlayerInv().player, item ) ); @@ -164,15 +167,15 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn } @Override - public ItemStack getStackInSlotOnClosing(int var1) + public ItemStack getStackInSlotOnClosing( int var1 ) { return null; } @Override - public void setInventorySlotContents(int var1, ItemStack var2) + public void setInventorySlotContents( int var1, ItemStack var2 ) { - if ( var2 == null && Platform.isServer() ) + if( var2 == null && Platform.isServer() ) this.makePlate(); } @@ -201,7 +204,7 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn } @Override - public boolean isUseableByPlayer(EntityPlayer var1) + public boolean isUseableByPlayer( EntityPlayer var1 ) { return false; } @@ -219,9 +222,8 @@ public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngIn } @Override - public boolean isItemValidForSlot(int var1, ItemStack var2) + public boolean isItemValidForSlot( int var1, ItemStack var2 ) { return false; } - } diff --git a/src/main/java/appeng/container/implementations/ContainerSecurity.java b/src/main/java/appeng/container/implementations/ContainerSecurity.java index da20a36e7..2bee5bce0 100644 --- a/src/main/java/appeng/container/implementations/ContainerSecurity.java +++ b/src/main/java/appeng/container/implementations/ContainerSecurity.java @@ -39,6 +39,7 @@ import appeng.tile.inventory.IAEAppEngInventory; import appeng.tile.inventory.InvOperation; import appeng.tile.misc.TileSecurity; + public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppEngInventory { @@ -50,8 +51,11 @@ public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppE final SlotOutput wirelessOut; final TileSecurity securityBox; + @GuiSync( 0 ) + public int security = 0; - public ContainerSecurity(InventoryPlayer ip, ITerminalHost monitorable) { + public ContainerSecurity( InventoryPlayer ip, ITerminalHost monitorable ) + { super( ip, monitorable, false ); this.securityBox = (TileSecurity) monitorable; @@ -64,38 +68,23 @@ public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppE this.bindPlayerInventory( ip, 0, 0 ); } - @GuiSync(0) - public int security = 0; - - @Override - public void onContainerClosed(EntityPlayer player) - { - super.onContainerClosed( player ); - - if ( this.wirelessIn.getHasStack() ) - player.dropPlayerItemWithRandomChoice( this.wirelessIn.getStack(), false ); - - if ( this.wirelessOut.getHasStack() ) - player.dropPlayerItemWithRandomChoice( this.wirelessOut.getStack(), false ); - } - - public void toggleSetting(String value, EntityPlayer player) + public void toggleSetting( String value, EntityPlayer player ) { try { SecurityPermissions permission = SecurityPermissions.valueOf( value ); ItemStack a = this.configSlot.getStack(); - if ( a != null && a.getItem() instanceof IBiometricCard ) + if( a != null && a.getItem() instanceof IBiometricCard ) { IBiometricCard bc = (IBiometricCard) a.getItem(); - if ( bc.hasPermission( a, permission ) ) + if( bc.hasPermission( a, permission ) ) bc.removePermission( a, permission ); else bc.addPermission( a, permission ); } } - catch (EnumConstantNotPresentException ex) + catch( EnumConstantNotPresentException ex ) { // :( } @@ -109,11 +98,11 @@ public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppE this.security = 0; ItemStack a = this.configSlot.getStack(); - if ( a != null && a.getItem() instanceof IBiometricCard ) + if( a != null && a.getItem() instanceof IBiometricCard ) { IBiometricCard bc = (IBiometricCard) a.getItem(); - for (SecurityPermissions sp : bc.getPermissions( a )) + for( SecurityPermissions sp : bc.getPermissions( a ) ) this.security |= ( 1 << sp.ordinal() ); } @@ -122,6 +111,18 @@ public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppE super.detectAndSendChanges(); } + @Override + public void onContainerClosed( EntityPlayer player ) + { + super.onContainerClosed( player ); + + if( this.wirelessIn.getHasStack() ) + player.dropPlayerItemWithRandomChoice( this.wirelessIn.getStack(), false ); + + if( this.wirelessOut.getHasStack() ) + player.dropPlayerItemWithRandomChoice( this.wirelessOut.getStack(), false ); + } + @Override public void saveChanges() { @@ -129,23 +130,23 @@ public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppE } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) { - if ( !this.wirelessOut.getHasStack() ) + if( !this.wirelessOut.getHasStack() ) { - if ( this.wirelessIn.getHasStack() ) + if( this.wirelessIn.getHasStack() ) { ItemStack term = this.wirelessIn.getStack().copy(); INetworkEncodable networkEncodable = null; - if ( term.getItem() instanceof INetworkEncodable ) + if( term.getItem() instanceof INetworkEncodable ) networkEncodable = (INetworkEncodable) term.getItem(); IWirelessTermHandler wTermHandler = AEApi.instance().registries().wireless().getWirelessTerminalHandler( term ); - if ( wTermHandler != null ) + if( wTermHandler != null ) networkEncodable = wTermHandler; - if ( networkEncodable != null ) + if( networkEncodable != null ) { networkEncodable.setEncryptionKey( term, String.valueOf( this.securityBox.securityKey ), "" ); @@ -153,14 +154,13 @@ public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppE this.wirelessOut.putStack( term ); // update the two slots in question... - for (Object crafter : this.crafters) + for( Object crafter : this.crafters ) { ICrafting icrafting = (ICrafting) crafter; icrafting.sendSlotContents( this, this.wirelessIn.slotNumber, this.wirelessIn.getStack() ); icrafting.sendSlotContents( this, this.wirelessOut.slotNumber, this.wirelessOut.getStack() ); } } - } } } diff --git a/src/main/java/appeng/container/implementations/ContainerSkyChest.java b/src/main/java/appeng/container/implementations/ContainerSkyChest.java index 2d27a0aef..de85dbc76 100644 --- a/src/main/java/appeng/container/implementations/ContainerSkyChest.java +++ b/src/main/java/appeng/container/implementations/ContainerSkyChest.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; @@ -27,19 +28,21 @@ import appeng.container.AEBaseContainer; import appeng.container.slot.SlotNormal; import appeng.tile.storage.TileSkyChest; + @ChestContainer public class ContainerSkyChest extends AEBaseContainer { final TileSkyChest chest; - public ContainerSkyChest(InventoryPlayer ip, TileSkyChest chest) { + public ContainerSkyChest( InventoryPlayer ip, TileSkyChest chest ) + { super( ip, chest, null ); this.chest = chest; - for (int y = 0; y < 4; y++) + for( int y = 0; y < 4; y++ ) { - for (int x = 0; x < 9; x++) + for( int x = 0; x < 9; x++ ) { this.addSlotToContainer( new SlotNormal( this.chest, y * 9 + x, 8 + 18 * x, 24 + 18 * y ) ); } @@ -51,7 +54,7 @@ public class ContainerSkyChest extends AEBaseContainer } @Override - public void onContainerClosed(EntityPlayer par1EntityPlayer) + public void onContainerClosed( EntityPlayer par1EntityPlayer ) { super.onContainerClosed( par1EntityPlayer ); this.chest.closeInventory(); diff --git a/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java b/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java index 49e300089..21f709ce8 100644 --- a/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java +++ b/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import net.minecraftforge.common.util.ForgeDirection; @@ -32,29 +33,28 @@ import appeng.container.slot.SlotRestrictedInput; import appeng.tile.spatial.TileSpatialIOPort; import appeng.util.Platform; + public class ContainerSpatialIOPort extends AEBaseContainer { final TileSpatialIOPort spatialIOPort; - - IGrid network; - - @GuiSync(0) + @GuiSync( 0 ) public long currentPower; - @GuiSync(1) + @GuiSync( 1 ) public long maxPower; - @GuiSync(2) + @GuiSync( 2 ) public long reqPower; - @GuiSync(3) + @GuiSync( 3 ) public long eff; - + IGrid network; int delay = 40; - public ContainerSpatialIOPort(InventoryPlayer ip, TileSpatialIOPort spatialIOPort) { + public ContainerSpatialIOPort( InventoryPlayer ip, TileSpatialIOPort spatialIOPort ) + { super( ip, spatialIOPort, null ); this.spatialIOPort = spatialIOPort; - if ( Platform.isServer() ) + if( Platform.isServer() ) this.network = spatialIOPort.getGridNode( ForgeDirection.UNKNOWN ).getGrid(); this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS, spatialIOPort, 0, 52, 48, this.invPlayer ) ); @@ -68,21 +68,21 @@ public class ContainerSpatialIOPort extends AEBaseContainer { this.verifyPermissions( SecurityPermissions.BUILD, false ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { this.delay++; - if ( this.delay > 15 && this.network != null ) + if( this.delay > 15 && this.network != null ) { this.delay = 0; IEnergyGrid eg = this.network.getCache( IEnergyGrid.class ); ISpatialCache sc = this.network.getCache( ISpatialCache.class ); - if ( eg != null ) + if( eg != null ) { - this.currentPower = (long) (100.0 * eg.getStoredPower()); - this.maxPower = (long) (100.0 * eg.getMaxStoredPower()); - this.reqPower = (long) (100.0 * sc.requiredPower()); - this.eff = (long) (100.0f * sc.currentEfficiency()); + this.currentPower = (long) ( 100.0 * eg.getStoredPower() ); + this.maxPower = (long) ( 100.0 * eg.getMaxStoredPower() ); + this.reqPower = (long) ( 100.0 * sc.requiredPower() ); + this.eff = (long) ( 100.0f * sc.currentEfficiency() ); } } } diff --git a/src/main/java/appeng/container/implementations/ContainerStorageBus.java b/src/main/java/appeng/container/implementations/ContainerStorageBus.java index 0b8ad816c..07c4641bc 100644 --- a/src/main/java/appeng/container/implementations/ContainerStorageBus.java +++ b/src/main/java/appeng/container/implementations/ContainerStorageBus.java @@ -43,18 +43,20 @@ import appeng.parts.misc.PartStorageBus; import appeng.util.Platform; import appeng.util.iterators.NullIterator; + public class ContainerStorageBus extends ContainerUpgradeable { final PartStorageBus storageBus; - @GuiSync(3) + @GuiSync( 3 ) public AccessRestriction rwMode = AccessRestriction.READ_WRITE; - @GuiSync(4) + @GuiSync( 4 ) public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; - public ContainerStorageBus(InventoryPlayer ip, PartStorageBus te) { + public ContainerStorageBus( InventoryPlayer ip, PartStorageBus te ) + { super( ip, te ); this.storageBus = te; } @@ -66,9 +68,29 @@ public class ContainerStorageBus extends ContainerUpgradeable } @Override - public int availableUpgrades() + protected void setupConfig() { - return 5; + int xo = 8; + int yo = 23 + 6; + + IInventory config = this.upgradeable.getInventoryByName( "config" ); + for( int y = 0; y < 7; y++ ) + { + for( int x = 0; x < 9; x++ ) + { + if( y < 2 ) + this.addSlotToContainer( new SlotFakeTypeOnly( config, y * 9 + x, xo + x * 18, yo + y * 18 ) ); + else + this.addSlotToContainer( new OptionalSlotFakeTypeOnly( config, this, y * 9 + x, xo, yo, x, y, y - 2 ) ); + } + } + + IInventory upgrades = this.upgradeable.getInventoryByName( "upgrades" ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.invPlayer ) ).setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.invPlayer ) ).setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.invPlayer ) ).setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.invPlayer ) ).setNotDraggable() ); + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.invPlayer ) ).setNotDraggable() ); } @Override @@ -78,37 +100,9 @@ public class ContainerStorageBus extends ContainerUpgradeable } @Override - public boolean isSlotEnabled(int idx) + public int availableUpgrades() { - int upgrades = this.upgradeable.getInstalledUpgrades( Upgrades.CAPACITY ); - - return upgrades > idx; - } - - @Override - protected void setupConfig() - { - int xo = 8; - int yo = 23 + 6; - - IInventory config = this.upgradeable.getInventoryByName( "config" ); - for (int y = 0; y < 7; y++) - { - for (int x = 0; x < 9; x++) - { - if ( y < 2 ) - this.addSlotToContainer( new SlotFakeTypeOnly( config, y * 9 + x, xo + x * 18, yo + y * 18 ) ); - else - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( config, this, y * 9 + x, xo, yo, x, y, y - 2 ) ); - } - } - - IInventory upgrades = this.upgradeable.getInventoryByName( "upgrades" ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.invPlayer )).setNotDraggable() ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.invPlayer )).setNotDraggable() ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.invPlayer )).setNotDraggable() ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.invPlayer )).setNotDraggable() ); - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.invPlayer )).setNotDraggable() ); + return 5; } @Override @@ -116,7 +110,7 @@ public class ContainerStorageBus extends ContainerUpgradeable { this.verifyPermissions( SecurityPermissions.BUILD, false ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { this.fzMode = (FuzzyMode) this.upgradeable.getConfigManager().getSetting( Settings.FUZZY_MODE ); this.rwMode = (AccessRestriction) this.upgradeable.getConfigManager().getSetting( Settings.ACCESS ); @@ -126,10 +120,18 @@ public class ContainerStorageBus extends ContainerUpgradeable this.standardDetectAndSendChanges(); } + @Override + public boolean isSlotEnabled( int idx ) + { + int upgrades = this.upgradeable.getInstalledUpgrades( Upgrades.CAPACITY ); + + return upgrades > idx; + } + public void clear() { IInventory inv = this.upgradeable.getInventoryByName( "config" ); - for (int x = 0; x < inv.getSizeInventory(); x++) + for( int x = 0; x < inv.getSizeInventory(); x++ ) inv.setInventorySlotContents( x, null ); this.detectAndSendChanges(); } @@ -141,15 +143,15 @@ public class ContainerStorageBus extends ContainerUpgradeable IMEInventory cellInv = this.storageBus.getInternalHandler(); Iterator i = new NullIterator(); - if ( cellInv != null ) + if( cellInv != null ) { IItemList list = cellInv.getAvailableItems( AEApi.instance().storage().createItemList() ); i = list.iterator(); } - for (int x = 0; x < inv.getSizeInventory(); x++) + for( int x = 0; x < inv.getSizeInventory(); x++ ) { - if ( i.hasNext() && this.isSlotEnabled( (x / 9) - 2 ) ) + if( i.hasNext() && this.isSlotEnabled( ( x / 9 ) - 2 ) ) { ItemStack g = i.next().getItemStack(); g.stackSize = 1; @@ -161,5 +163,4 @@ public class ContainerStorageBus extends ContainerUpgradeable this.detectAndSendChanges(); } - } diff --git a/src/main/java/appeng/container/implementations/ContainerUpgradeable.java b/src/main/java/appeng/container/implementations/ContainerUpgradeable.java index e31ac088d..58613574e 100644 --- a/src/main/java/appeng/container/implementations/ContainerUpgradeable.java +++ b/src/main/java/appeng/container/implementations/ContainerUpgradeable.java @@ -46,16 +46,23 @@ import appeng.items.tools.ToolNetworkTool; import appeng.parts.automation.PartExportBus; import appeng.util.Platform; + public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSlotHost { final IUpgradeableHost upgradeable; - + @GuiSync( 0 ) + public RedstoneMode rsMode = RedstoneMode.IGNORE; + @GuiSync( 1 ) + public FuzzyMode fzMode = FuzzyMode.IGNORE_ALL; + @GuiSync( 5 ) + public YesNo cMode = YesNo.NO; int tbSlot; NetworkToolViewer tbInventory; - public ContainerUpgradeable(InventoryPlayer ip, IUpgradeableHost te) { - super( ip, (TileEntity) (te instanceof TileEntity ? te : null), (IPart) (te instanceof IPart ? te : null) ); + public ContainerUpgradeable( InventoryPlayer ip, IUpgradeableHost te ) + { + super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); this.upgradeable = te; World w = null; @@ -63,7 +70,7 @@ public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSl int yCoord = 0; int zCoord = 0; - if ( te instanceof TileEntity ) + if( te instanceof TileEntity ) { TileEntity myTile = (TileEntity) te; w = myTile.getWorldObj(); @@ -72,7 +79,7 @@ public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSl zCoord = myTile.zCoord; } - if ( te instanceof IPart ) + if( te instanceof IPart ) { TileEntity mk = te.getTile(); w = mk.getWorldObj(); @@ -82,24 +89,23 @@ public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSl } IInventory pi = this.getPlayerInv(); - for (int x = 0; x < pi.getSizeInventory(); x++) + for( int x = 0; x < pi.getSizeInventory(); x++ ) { ItemStack pii = pi.getStackInSlot( x ); - if ( pii != null && pii.getItem() instanceof ToolNetworkTool ) + if( pii != null && pii.getItem() instanceof ToolNetworkTool ) { this.lockPlayerInventorySlot( x ); this.tbSlot = x; - this.tbInventory = (NetworkToolViewer) ((ToolNetworkTool) pii.getItem()).getGuiObject( pii, w, xCoord, yCoord, zCoord ); + this.tbInventory = (NetworkToolViewer) ( (ToolNetworkTool) pii.getItem() ).getGuiObject( pii, w, xCoord, yCoord, zCoord ); break; } } - if ( this.hasToolbox() ) + if( this.hasToolbox() ) { - for (int v = 0; v < 3; v++) - for (int u = 0; u < 3; u++) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, this.tbInventory, u + v * 3, 186 + u * 18, this.getHeight() - 82 + v * 18, - this.invPlayer )).setPlayerSide() ); + for( int v = 0; v < 3; v++ ) + for( int u = 0; u < 3; u++ ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, this.tbInventory, u + v * 3, 186 + u * 18, this.getHeight() - 82 + v * 18, this.invPlayer ) ).setPlayerSide() ); } this.setupConfig(); @@ -107,17 +113,14 @@ public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSl this.bindPlayerInventory( ip, 0, this.getHeight() - /* height of player inventory */82 ); } - protected void setupUpgrades() + public boolean hasToolbox() { - IInventory upgrades = this.upgradeable.getInventoryByName( "upgrades" ); - if ( this.availableUpgrades() > 0 ) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.invPlayer )).setNotDraggable() ); - if ( this.availableUpgrades() > 1 ) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.invPlayer )).setNotDraggable() ); - if ( this.availableUpgrades() > 2 ) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.invPlayer )).setNotDraggable() ); - if ( this.availableUpgrades() > 3 ) - this.addSlotToContainer( (new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.invPlayer )).setNotDraggable() ); + return this.tbInventory != null; + } + + protected int getHeight() + { + return 184; } protected void setupConfig() @@ -129,7 +132,7 @@ public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSl IInventory inv = this.upgradeable.getInventoryByName( "config" ); this.addSlotToContainer( new SlotFakeTypeOnly( inv, 0, x, y ) ); - if ( this.supportCapacity() ) + if( this.supportCapacity() ) { this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 1, x, y, -1, 0, 1 ) ); this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 2, x, y, 1, 0, 1 ) ); @@ -143,14 +146,17 @@ public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSl } } - protected int getHeight() + protected void setupUpgrades() { - return 184; - } - - public int availableUpgrades() - { - return 4; + IInventory upgrades = this.upgradeable.getInventoryByName( "upgrades" ); + if( this.availableUpgrades() > 0 ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.invPlayer ) ).setNotDraggable() ); + if( this.availableUpgrades() > 1 ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.invPlayer ) ).setNotDraggable() ); + if( this.availableUpgrades() > 2 ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.invPlayer ) ).setNotDraggable() ); + if( this.availableUpgrades() > 3 ) + this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.invPlayer ) ).setNotDraggable() ); } protected boolean supportCapacity() @@ -158,26 +164,56 @@ public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSl return true; } - @GuiSync(0) - public RedstoneMode rsMode = RedstoneMode.IGNORE; + public int availableUpgrades() + { + return 4; + } - @GuiSync(1) - public FuzzyMode fzMode = FuzzyMode.IGNORE_ALL; + @Override + public void detectAndSendChanges() + { + this.verifyPermissions( SecurityPermissions.BUILD, false ); - @GuiSync(5) - public YesNo cMode = YesNo.NO; + if( Platform.isServer() ) + { + IConfigManager cm = this.upgradeable.getConfigManager(); + this.loadSettingsFromHost( cm ); + } + + this.checkToolbox(); + + for( Object o : this.inventorySlots ) + { + if( o instanceof OptionalSlotFake ) + { + OptionalSlotFake fs = (OptionalSlotFake) o; + if( !fs.isEnabled() && fs.getDisplayStack() != null ) + fs.clearStack(); + } + } + + this.standardDetectAndSendChanges(); + } + + protected void loadSettingsFromHost( IConfigManager cm ) + { + this.fzMode = (FuzzyMode) cm.getSetting( Settings.FUZZY_MODE ); + this.rsMode = (RedstoneMode) cm.getSetting( Settings.REDSTONE_CONTROLLED ); + if( this.upgradeable instanceof PartExportBus ) + this.cMode = (YesNo) cm.getSetting( Settings.CRAFT_ONLY ); + } public void checkToolbox() { - if ( this.hasToolbox() ) + if( this.hasToolbox() ) { ItemStack currentItem = this.getPlayerInv().getStackInSlot( this.tbSlot ); - if ( currentItem != this.tbInventory.getItemStack() ) + if( currentItem != this.tbInventory.getItemStack() ) { - if ( currentItem != null ) + if( currentItem != null ) { - if ( Platform.isSameItem( this.tbInventory.getItemStack(), currentItem ) ) + if( Platform.isSameItem( this.tbInventory.getItemStack(), currentItem ) ) this.getPlayerInv().setInventorySlotContents( this.tbSlot, this.tbInventory.getItemStack() ); else this.isContainerValid = false; @@ -188,61 +224,21 @@ public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSl } } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - - if ( Platform.isServer() ) - { - IConfigManager cm = this.upgradeable.getConfigManager(); - this.loadSettingsFromHost( cm ); - } - - this.checkToolbox(); - - for (Object o : this.inventorySlots) - { - if ( o instanceof OptionalSlotFake ) - { - OptionalSlotFake fs = (OptionalSlotFake) o; - if ( !fs.isEnabled() && fs.getDisplayStack() != null ) - fs.clearStack(); - } - } - - this.standardDetectAndSendChanges(); - } - - protected void loadSettingsFromHost(IConfigManager cm) - { - this.fzMode = (FuzzyMode) cm.getSetting( Settings.FUZZY_MODE ); - this.rsMode = (RedstoneMode) cm.getSetting( Settings.REDSTONE_CONTROLLED ); - if ( this.upgradeable instanceof PartExportBus ) - this.cMode = (YesNo) cm.getSetting( Settings.CRAFT_ONLY ); - } - protected void standardDetectAndSendChanges() { super.detectAndSendChanges(); } - public boolean hasToolbox() - { - return this.tbInventory != null; - } - @Override - public boolean isSlotEnabled(int idx) + public boolean isSlotEnabled( int idx ) { int upgrades = this.upgradeable.getInstalledUpgrades( Upgrades.CAPACITY ); - if ( idx == 1 && upgrades > 0 ) + if( idx == 1 && upgrades > 0 ) return true; - if ( idx == 2 && upgrades > 1 ) + if( idx == 2 && upgrades > 1 ) return true; return false; } - } diff --git a/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java b/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java index 2fe0c65b2..38794a652 100644 --- a/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java +++ b/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.container.AEBaseContainer; @@ -27,13 +28,20 @@ import appeng.container.slot.SlotRestrictedInput; import appeng.tile.misc.TileVibrationChamber; import appeng.util.Platform; + public class ContainerVibrationChamber extends AEBaseContainer implements IProgressProvider { - final TileVibrationChamber vibrationChamber; private static final int MAX_BURN_TIME = 200; + public final int aePerTick = 5; + final TileVibrationChamber vibrationChamber; + @GuiSync( 0 ) + public int burnProgress = 0; + @GuiSync( 1 ) + public int burnSpeed = 100; - public ContainerVibrationChamber(InventoryPlayer ip, TileVibrationChamber vibrationChamber) { + public ContainerVibrationChamber( InventoryPlayer ip, TileVibrationChamber vibrationChamber ) + { super( ip, vibrationChamber, null ); this.vibrationChamber = vibrationChamber; @@ -42,20 +50,12 @@ public class ContainerVibrationChamber extends AEBaseContainer implements IProgr this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); } - public final int aePerTick = 5; - - @GuiSync(0) - public int burnProgress = 0; - - @GuiSync(1) - public int burnSpeed = 100; - @Override public void detectAndSendChanges() { - if ( Platform.isServer() ) + if( Platform.isServer() ) { - this.burnProgress = (int) (this.vibrationChamber.maxBurnTime <= 0 ? 0 : 12 * this.vibrationChamber.burnTime / this.vibrationChamber.maxBurnTime); + this.burnProgress = (int) ( this.vibrationChamber.maxBurnTime <= 0 ? 0 : 12 * this.vibrationChamber.burnTime / this.vibrationChamber.maxBurnTime ); this.burnSpeed = this.vibrationChamber.burnSpeed; } @@ -73,5 +73,4 @@ public class ContainerVibrationChamber extends AEBaseContainer implements IProgr { return MAX_BURN_TIME; } - } diff --git a/src/main/java/appeng/container/implementations/ContainerWireless.java b/src/main/java/appeng/container/implementations/ContainerWireless.java index af0f38f41..4352d19a8 100644 --- a/src/main/java/appeng/container/implementations/ContainerWireless.java +++ b/src/main/java/appeng/container/implementations/ContainerWireless.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.container.AEBaseContainer; @@ -26,20 +27,19 @@ import appeng.container.slot.SlotRestrictedInput; import appeng.core.AEConfig; import appeng.tile.networking.TileWireless; + public class ContainerWireless extends AEBaseContainer { final TileWireless wirelessTerminal; - - @GuiSync(1) + final SlotRestrictedInput boosterSlot; + @GuiSync( 1 ) public long range = 0; - - @GuiSync(2) + @GuiSync( 2 ) public long drain = 0; - final SlotRestrictedInput boosterSlot; - - public ContainerWireless(InventoryPlayer ip, TileWireless te) { + public ContainerWireless( InventoryPlayer ip, TileWireless te ) + { super( ip, te, null ); this.wirelessTerminal = te; @@ -53,10 +53,9 @@ public class ContainerWireless extends AEBaseContainer { int boosters = this.boosterSlot.getStack() == null ? 0 : this.boosterSlot.getStack().stackSize; - this.range = (long) (10 * AEConfig.instance.wireless_getMaxRange( boosters )); - this.drain = (long) (100 * AEConfig.instance.wireless_getPowerDrain( boosters )); + this.range = (long) ( 10 * AEConfig.instance.wireless_getMaxRange( boosters ) ); + this.drain = (long) ( 100 * AEConfig.instance.wireless_getPowerDrain( boosters ) ); super.detectAndSendChanges(); } - } diff --git a/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java b/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java index 43644fbe2..f05985d95 100644 --- a/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java @@ -18,6 +18,7 @@ package appeng.container.implementations; + import net.minecraft.entity.player.InventoryPlayer; import appeng.core.AEConfig; @@ -25,12 +26,14 @@ import appeng.core.localization.PlayerMessages; import appeng.helpers.WirelessTerminalGuiObject; import appeng.util.Platform; + public class ContainerWirelessTerm extends ContainerMEPortableCell { final WirelessTerminalGuiObject wirelessTerminalGUIObject; - public ContainerWirelessTerm(InventoryPlayer ip, WirelessTerminalGuiObject wirelessTerminalGUIObject) { + public ContainerWirelessTerm( InventoryPlayer ip, WirelessTerminalGuiObject wirelessTerminalGUIObject ) + { super( ip, wirelessTerminalGUIObject ); this.wirelessTerminalGUIObject = wirelessTerminalGUIObject; } @@ -40,9 +43,9 @@ public class ContainerWirelessTerm extends ContainerMEPortableCell { super.detectAndSendChanges(); - if ( !this.wirelessTerminalGUIObject.rangeCheck() ) + if( !this.wirelessTerminalGUIObject.rangeCheck() ) { - if ( Platform.isServer() && this.isContainerValid ) + if( Platform.isServer() && this.isContainerValid ) this.getPlayerInv().player.addChatMessage( PlayerMessages.OutOfRange.get() ); this.isContainerValid = false; diff --git a/src/main/java/appeng/container/implementations/CraftingCPURecord.java b/src/main/java/appeng/container/implementations/CraftingCPURecord.java index 29d4b33fd..04d61ea23 100644 --- a/src/main/java/appeng/container/implementations/CraftingCPURecord.java +++ b/src/main/java/appeng/container/implementations/CraftingCPURecord.java @@ -18,20 +18,21 @@ package appeng.container.implementations; + import appeng.api.networking.crafting.ICraftingCPU; import appeng.util.ItemSorters; + public class CraftingCPURecord implements Comparable { + public final String myName; final ICraftingCPU cpu; - final long size; final int processors; - public final String myName; - - public CraftingCPURecord(long size, int coProcessors, ICraftingCPU server) { + public CraftingCPURecord( long size, int coProcessors, ICraftingCPU server ) + { this.size = size; this.processors = coProcessors; this.cpu = server; @@ -39,12 +40,11 @@ public class CraftingCPURecord implements Comparable } @Override - public int compareTo(CraftingCPURecord o) + public int compareTo( CraftingCPURecord o ) { int a = ItemSorters.compareLong( o.processors, this.processors ); - if ( a != 0 ) + if( a != 0 ) return a; return ItemSorters.compareLong( o.size, this.size ); } - } \ No newline at end of file diff --git a/src/main/java/appeng/container/interfaces/IProgressProvider.java b/src/main/java/appeng/container/interfaces/IProgressProvider.java index e4de8067e..4dbb294a7 100644 --- a/src/main/java/appeng/container/interfaces/IProgressProvider.java +++ b/src/main/java/appeng/container/interfaces/IProgressProvider.java @@ -18,14 +18,15 @@ package appeng.container.interfaces; + import appeng.client.gui.widgets.GuiProgressBar; + /** * This interface provides the data for anything simulating a progress. * * Its main use is in combination with the {@link GuiProgressBar}, which ensures to scale it to a percentage of 0 to * 100. - * */ public interface IProgressProvider { @@ -46,5 +47,4 @@ public interface IProgressProvider * @return An int representing the max progress */ int getMaxProgress(); - } diff --git a/src/main/java/appeng/container/slot/AppEngCraftingSlot.java b/src/main/java/appeng/container/slot/AppEngCraftingSlot.java index d3e355711..b5b7b2297 100644 --- a/src/main/java/appeng/container/slot/AppEngCraftingSlot.java +++ b/src/main/java/appeng/container/slot/AppEngCraftingSlot.java @@ -18,6 +18,7 @@ package appeng.container.slot; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; @@ -33,13 +34,18 @@ import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import cpw.mods.fml.common.FMLCommonHandler; + public class AppEngCraftingSlot extends AppEngSlot { - /** The craft matrix inventory linked to this result slot. */ + /** + * The craft matrix inventory linked to this result slot. + */ private final IInventory craftMatrix; - /** The player that is using the GUI where this slot resides. */ + /** + * The player that is using the GUI where this slot resides. + */ private final EntityPlayer thePlayer; /** @@ -47,7 +53,8 @@ public class AppEngCraftingSlot extends AppEngSlot */ private int amountCrafted; - public AppEngCraftingSlot(EntityPlayer par1EntityPlayer, IInventory par2IInventory, IInventory par3IInventory, int par4, int par5, int par6) { + public AppEngCraftingSlot( EntityPlayer par1EntityPlayer, IInventory par2IInventory, IInventory par3IInventory, int par4, int par5, int par6 ) + { super( par3IInventory, par4, par5, par6 ); this.thePlayer = par1EntityPlayer; this.craftMatrix = par2IInventory; @@ -57,32 +64,17 @@ public class AppEngCraftingSlot extends AppEngSlot * Check if the stack is a valid item for this slot. Always true beside for the armor slots. */ @Override - public boolean isItemValid(ItemStack par1ItemStack) + public boolean isItemValid( ItemStack par1ItemStack ) { return false; } - /** - * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new - * stack. - */ - @Override - public ItemStack decrStackSize(int par1) - { - if ( this.getHasStack() ) - { - this.amountCrafted += Math.min( par1, this.getStack().stackSize ); - } - - return super.decrStackSize( par1 ); - } - /** * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an * internal count then calls onCrafting(item). */ @Override - protected void onCrafting(ItemStack par1ItemStack, int par2) + protected void onCrafting( ItemStack par1ItemStack, int par2 ) { this.amountCrafted += par2; this.onCrafting( par1ItemStack ); @@ -92,90 +84,89 @@ public class AppEngCraftingSlot extends AppEngSlot * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. */ @Override - protected void onCrafting(ItemStack par1ItemStack) + protected void onCrafting( ItemStack par1ItemStack ) { par1ItemStack.onCrafting( this.thePlayer.worldObj, this.thePlayer, this.amountCrafted ); this.amountCrafted = 0; - if ( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.crafting_table ) ) + if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.crafting_table ) ) { this.thePlayer.addStat( AchievementList.buildWorkBench, 1 ); } - if ( par1ItemStack.getItem() instanceof ItemPickaxe ) + if( par1ItemStack.getItem() instanceof ItemPickaxe ) { this.thePlayer.addStat( AchievementList.buildPickaxe, 1 ); } - if ( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.furnace ) ) + if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.furnace ) ) { this.thePlayer.addStat( AchievementList.buildFurnace, 1 ); } - if ( par1ItemStack.getItem() instanceof ItemHoe ) + if( par1ItemStack.getItem() instanceof ItemHoe ) { this.thePlayer.addStat( AchievementList.buildHoe, 1 ); } - if ( par1ItemStack.getItem() == Items.bread ) + if( par1ItemStack.getItem() == Items.bread ) { this.thePlayer.addStat( AchievementList.makeBread, 1 ); } - if ( par1ItemStack.getItem() == Items.cake ) + if( par1ItemStack.getItem() == Items.cake ) { this.thePlayer.addStat( AchievementList.bakeCake, 1 ); } - if ( par1ItemStack.getItem() instanceof ItemPickaxe && ((ItemPickaxe) par1ItemStack.getItem()).func_150913_i() != Item.ToolMaterial.WOOD ) + if( par1ItemStack.getItem() instanceof ItemPickaxe && ( (ItemPickaxe) par1ItemStack.getItem() ).func_150913_i() != Item.ToolMaterial.WOOD ) { this.thePlayer.addStat( AchievementList.buildBetterPickaxe, 1 ); } - if ( par1ItemStack.getItem() instanceof ItemSword ) + if( par1ItemStack.getItem() instanceof ItemSword ) { this.thePlayer.addStat( AchievementList.buildSword, 1 ); } - if ( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.enchanting_table ) ) + if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.enchanting_table ) ) { this.thePlayer.addStat( AchievementList.enchantments, 1 ); } - if ( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.bookshelf ) ) + if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.bookshelf ) ) { this.thePlayer.addStat( AchievementList.bookcase, 1 ); } } @Override - public void onPickupFromSlot(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack) + public void onPickupFromSlot( EntityPlayer par1EntityPlayer, ItemStack par2ItemStack ) { FMLCommonHandler.instance().firePlayerCraftingEvent( par1EntityPlayer, par2ItemStack, this.craftMatrix ); this.onCrafting( par2ItemStack ); - for (int i = 0; i < this.craftMatrix.getSizeInventory(); ++i) + for( int i = 0; i < this.craftMatrix.getSizeInventory(); ++i ) { ItemStack itemstack1 = this.craftMatrix.getStackInSlot( i ); - if ( itemstack1 != null ) + if( itemstack1 != null ) { this.craftMatrix.decrStackSize( i, 1 ); - if ( itemstack1.getItem().hasContainerItem( itemstack1 ) ) + if( itemstack1.getItem().hasContainerItem( itemstack1 ) ) { ItemStack itemstack2 = itemstack1.getItem().getContainerItem( itemstack1 ); - if ( itemstack2 != null && itemstack2.isItemStackDamageable() && itemstack2.getItemDamage() > itemstack2.getMaxDamage() ) + if( itemstack2 != null && itemstack2.isItemStackDamageable() && itemstack2.getItemDamage() > itemstack2.getMaxDamage() ) { MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( this.thePlayer, itemstack2 ) ); continue; } - if ( !itemstack1.getItem().doesContainerItemLeaveCraftingGrid( itemstack1 ) - || !this.thePlayer.inventory.addItemStackToInventory( itemstack2 ) ) + if( !itemstack1.getItem().doesContainerItemLeaveCraftingGrid( itemstack1 ) || !this.thePlayer.inventory.addItemStackToInventory( itemstack2 ) ) { - if ( this.craftMatrix.getStackInSlot( i ) == null ) + if( this.craftMatrix.getStackInSlot( i ) == null ) { this.craftMatrix.setInventorySlotContents( i, itemstack2 ); } @@ -188,4 +179,19 @@ public class AppEngCraftingSlot extends AppEngSlot } } } + + /** + * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new + * stack. + */ + @Override + public ItemStack decrStackSize( int par1 ) + { + if( this.getHasStack() ) + { + this.amountCrafted += Math.min( par1, this.getStack().stackSize ); + } + + return super.decrStackSize( par1 ); + } } diff --git a/src/main/java/appeng/container/slot/AppEngSlot.java b/src/main/java/appeng/container/slot/AppEngSlot.java index 2e153b100..2ac0800ed 100644 --- a/src/main/java/appeng/container/slot/AppEngSlot.java +++ b/src/main/java/appeng/container/slot/AppEngSlot.java @@ -18,6 +18,7 @@ package appeng.container.slot; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; @@ -26,17 +27,26 @@ import net.minecraft.item.ItemStack; import appeng.container.AEBaseContainer; import appeng.tile.inventory.AppEngInternalInventory; + public class AppEngSlot extends Slot { - public enum hasCalculatedValidness - { - NotAvailable, Valid, Invalid - } - + public final int defX; + public final int defY; public boolean isDraggable = true; public boolean isPlayerSide = false; public AEBaseContainer myContainer = null; + public int IIcon = -1; + public hasCalculatedValidness isValid; + public boolean isDisplay = false; + + public AppEngSlot( IInventory inv, int idx, int x, int y ) + { + super( inv, idx, x, y ); + this.defX = x; + this.defY = y; + this.isValid = hasCalculatedValidness.NotAvailable; + } public Slot setNotDraggable() { @@ -50,95 +60,76 @@ public class AppEngSlot extends Slot return this; } - public int IIcon = -1; - public hasCalculatedValidness isValid; - public final int defX; - public final int defY; - - @Override - public boolean func_111238_b() - { - return this.isEnabled(); - } - - public boolean isEnabled() - { - return true; - } - public String getTooltip() { return null; } - @Override - public void onSlotChanged() - { - if ( this.inventory instanceof AppEngInternalInventory ) - ((AppEngInternalInventory) this.inventory).markDirty( this.getSlotIndex() ); - else - super.onSlotChanged(); - - this.isValid = hasCalculatedValidness.NotAvailable; - } - - public AppEngSlot(IInventory inv, int idx, int x, int y) { - super( inv, idx, x, y ); - this.defX = x; - this.defY = y; - this.isValid = hasCalculatedValidness.NotAvailable; - } - - public boolean isDisplay = false; - - @Override - public ItemStack getStack() - { - if ( !this.isEnabled() ) - return null; - - if ( this.inventory.getSizeInventory() <= this.getSlotIndex() ) - return null; - - if ( this.isDisplay ) - { - this.isDisplay = false; - return this.getDisplayStack(); - } - return super.getStack(); - } - - @Override - public void putStack(ItemStack par1ItemStack) - { - if ( this.isEnabled() ) - { - super.putStack( par1ItemStack ); - - if ( this.myContainer != null ) - this.myContainer.onSlotChange( this ); - } - } - public void clearStack() { super.putStack( null ); } @Override - public boolean canTakeStack(EntityPlayer par1EntityPlayer) + public boolean isItemValid( ItemStack par1ItemStack ) { - if ( this.isEnabled() ) + if( this.isEnabled() ) + return super.isItemValid( par1ItemStack ); + return false; + } + + @Override + public ItemStack getStack() + { + if( !this.isEnabled() ) + return null; + + if( this.inventory.getSizeInventory() <= this.getSlotIndex() ) + return null; + + if( this.isDisplay ) + { + this.isDisplay = false; + return this.getDisplayStack(); + } + return super.getStack(); + } + + @Override + public void putStack( ItemStack par1ItemStack ) + { + if( this.isEnabled() ) + { + super.putStack( par1ItemStack ); + + if( this.myContainer != null ) + this.myContainer.onSlotChange( this ); + } + } + + @Override + public void onSlotChanged() + { + if( this.inventory instanceof AppEngInternalInventory ) + ( (AppEngInternalInventory) this.inventory ).markDirty( this.getSlotIndex() ); + else + super.onSlotChanged(); + + this.isValid = hasCalculatedValidness.NotAvailable; + } + + @Override + public boolean canTakeStack( EntityPlayer par1EntityPlayer ) + { + if( this.isEnabled() ) return super.canTakeStack( par1EntityPlayer ); return false; } @Override - public boolean isItemValid(ItemStack par1ItemStack) + public boolean func_111238_b() { - if ( this.isEnabled() ) - return super.isItemValid( par1ItemStack ); - return false; + return this.isEnabled(); } public ItemStack getDisplayStack() @@ -146,6 +137,11 @@ public class AppEngSlot extends Slot return super.getStack(); } + public boolean isEnabled() + { + return true; + } + public float getOpacityOfIcon() { return 0.4f; @@ -171,4 +167,8 @@ public class AppEngSlot extends Slot return this.isEnabled(); } + public enum hasCalculatedValidness + { + NotAvailable, Valid, Invalid + } } diff --git a/src/main/java/appeng/container/slot/IOptionalSlotHost.java b/src/main/java/appeng/container/slot/IOptionalSlotHost.java index 18597cc9f..995959ce0 100644 --- a/src/main/java/appeng/container/slot/IOptionalSlotHost.java +++ b/src/main/java/appeng/container/slot/IOptionalSlotHost.java @@ -18,9 +18,9 @@ package appeng.container.slot; + public interface IOptionalSlotHost { - boolean isSlotEnabled(int idx); - + boolean isSlotEnabled( int idx ); } diff --git a/src/main/java/appeng/container/slot/NullSlot.java b/src/main/java/appeng/container/slot/NullSlot.java index 33b8ce3b6..0645e05df 100644 --- a/src/main/java/appeng/container/slot/NullSlot.java +++ b/src/main/java/appeng/container/slot/NullSlot.java @@ -18,32 +18,35 @@ package appeng.container.slot; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; + public class NullSlot extends Slot { - public NullSlot() { + public NullSlot() + { super( null, 0, 0, 0 ); } @Override - public void onSlotChange(ItemStack par1ItemStack, ItemStack par2ItemStack) + public void onSlotChange( ItemStack par1ItemStack, ItemStack par2ItemStack ) { } @Override - public void onPickupFromSlot(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack) + public void onPickupFromSlot( EntityPlayer par1EntityPlayer, ItemStack par2ItemStack ) { } @Override - public boolean isItemValid(ItemStack par1ItemStack) + public boolean isItemValid( ItemStack par1ItemStack ) { return false; } @@ -55,7 +58,7 @@ public class NullSlot extends Slot } @Override - public void putStack(ItemStack par1ItemStack) + public void putStack( ItemStack par1ItemStack ) { } @@ -73,19 +76,19 @@ public class NullSlot extends Slot } @Override - public ItemStack decrStackSize(int par1) + public ItemStack decrStackSize( int par1 ) { return null; } @Override - public boolean isSlotInInventory(IInventory par1IInventory, int par2) + public boolean isSlotInInventory( IInventory par1IInventory, int par2 ) { return false; } @Override - public boolean canTakeStack(EntityPlayer par1EntityPlayer) + public boolean canTakeStack( EntityPlayer par1EntityPlayer ) { return false; } diff --git a/src/main/java/appeng/container/slot/OptionalSlotFake.java b/src/main/java/appeng/container/slot/OptionalSlotFake.java index b2d2f7520..89d90f1b1 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotFake.java +++ b/src/main/java/appeng/container/slot/OptionalSlotFake.java @@ -18,22 +18,23 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class OptionalSlotFake extends SlotFake { + public final int srcX; + public final int srcY; final int invSlot; final int groupNum; final IOptionalSlotHost host; - public boolean renderDisabled = true; - public final int srcX; - public final int srcY; - - public OptionalSlotFake(IInventory inv, IOptionalSlotHost containerBus, int idx, int x, int y, int offX, int offY, int groupNum) { + public OptionalSlotFake( IInventory inv, IOptionalSlotHost containerBus, int idx, int x, int y, int offX, int offY, int groupNum ) + { super( inv, idx, x + offX * 18, y + offY * 18 ); this.srcX = x; this.srcY = y; @@ -45,9 +46,9 @@ public class OptionalSlotFake extends SlotFake @Override public ItemStack getStack() { - if ( !this.isEnabled() ) + if( !this.isEnabled() ) { - if ( this.getDisplayStack() != null ) + if( this.getDisplayStack() != null ) this.clearStack(); } @@ -57,7 +58,7 @@ public class OptionalSlotFake extends SlotFake @Override public boolean isEnabled() { - if ( this.host == null ) + if( this.host == null ) return false; return this.host.isSlotEnabled( this.groupNum ); @@ -67,5 +68,4 @@ public class OptionalSlotFake extends SlotFake { return this.renderDisabled; } - } diff --git a/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java b/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java index 6c56cf6be..182895aac 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java +++ b/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java @@ -18,25 +18,28 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class OptionalSlotFakeTypeOnly extends OptionalSlotFake { - public OptionalSlotFakeTypeOnly(IInventory inv, IOptionalSlotHost containerBus, int idx, int x, int y, int offX, int offY, int groupNum) { + public OptionalSlotFakeTypeOnly( IInventory inv, IOptionalSlotHost containerBus, int idx, int x, int y, int offX, int offY, int groupNum ) + { super( inv, containerBus, idx, x, y, offX, offY, groupNum ); } @Override - public void putStack(ItemStack is) + public void putStack( ItemStack is ) { - if ( is != null ) + if( is != null ) { is = is.copy(); - if ( is.stackSize > 1 ) + if( is.stackSize > 1 ) is.stackSize = 1; - else if ( is.stackSize < -1 ) + else if( is.stackSize < -1 ) is.stackSize = -1; } diff --git a/src/main/java/appeng/container/slot/OptionalSlotNormal.java b/src/main/java/appeng/container/slot/OptionalSlotNormal.java index ed8af4eb0..ca25b26e7 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotNormal.java +++ b/src/main/java/appeng/container/slot/OptionalSlotNormal.java @@ -18,15 +18,18 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; + public class OptionalSlotNormal extends AppEngSlot { final int groupNum; final IOptionalSlotHost host; - public OptionalSlotNormal(IInventory inv, IOptionalSlotHost containerBus, int slot, int xPos, int yPos, int groupNum) { + public OptionalSlotNormal( IInventory inv, IOptionalSlotHost containerBus, int slot, int xPos, int yPos, int groupNum ) + { super( inv, slot, xPos, yPos ); this.groupNum = groupNum; this.host = containerBus; @@ -35,10 +38,9 @@ public class OptionalSlotNormal extends AppEngSlot @Override public boolean isEnabled() { - if ( this.host == null ) + if( this.host == null ) return false; return this.host.isSlotEnabled( this.groupNum ); } - } diff --git a/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java b/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java index 1c997f919..26077b7f2 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java +++ b/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java @@ -18,17 +18,19 @@ package appeng.container.slot; + import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; + public class OptionalSlotRestrictedInput extends SlotRestrictedInput { final int groupNum; final IOptionalSlotHost host; - public OptionalSlotRestrictedInput(PlacableItemType valid, IInventory i, IOptionalSlotHost host, int slotIndex, int x, int y, int grpNum, - InventoryPlayer invPlayer) { + public OptionalSlotRestrictedInput( PlacableItemType valid, IInventory i, IOptionalSlotHost host, int slotIndex, int x, int y, int grpNum, InventoryPlayer invPlayer ) + { super( valid, i, slotIndex, x, y, invPlayer ); this.groupNum = grpNum; this.host = host; @@ -37,10 +39,9 @@ public class OptionalSlotRestrictedInput extends SlotRestrictedInput @Override public boolean isEnabled() { - if ( this.host == null ) + if( this.host == null ) return false; return this.host.isSlotEnabled( this.groupNum ); } - } diff --git a/src/main/java/appeng/container/slot/QuartzKnifeOutput.java b/src/main/java/appeng/container/slot/QuartzKnifeOutput.java index b629b7362..8e793852c 100644 --- a/src/main/java/appeng/container/slot/QuartzKnifeOutput.java +++ b/src/main/java/appeng/container/slot/QuartzKnifeOutput.java @@ -18,13 +18,15 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; + public class QuartzKnifeOutput extends SlotOutput { - public QuartzKnifeOutput(IInventory a, int b, int c, int d, int i) { + public QuartzKnifeOutput( IInventory a, int b, int c, int d, int i ) + { super( a, b, c, d, i ); } - } diff --git a/src/main/java/appeng/container/slot/SlotCraftingMatrix.java b/src/main/java/appeng/container/slot/SlotCraftingMatrix.java index 74e684cac..de23c969c 100644 --- a/src/main/java/appeng/container/slot/SlotCraftingMatrix.java +++ b/src/main/java/appeng/container/slot/SlotCraftingMatrix.java @@ -18,26 +18,23 @@ package appeng.container.slot; + import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class SlotCraftingMatrix extends AppEngSlot { final Container c; - public SlotCraftingMatrix(Container c, IInventory par1iInventory, int par2, int par3, int par4) { + public SlotCraftingMatrix( Container c, IInventory par1iInventory, int par2, int par3, int par4 ) + { super( par1iInventory, par2, par3, par4 ); this.c = c; } - @Override - public boolean isPlayerSide() - { - return true; - } - @Override public void clearStack() { @@ -46,18 +43,23 @@ public class SlotCraftingMatrix extends AppEngSlot } @Override - public ItemStack decrStackSize(int par1) - { - ItemStack is = super.decrStackSize( par1 ); - this.c.onCraftMatrixChanged( this.inventory ); - return is; - } - - @Override - public void putStack(ItemStack par1ItemStack) + public void putStack( ItemStack par1ItemStack ) { super.putStack( par1ItemStack ); this.c.onCraftMatrixChanged( this.inventory ); } + @Override + public boolean isPlayerSide() + { + return true; + } + + @Override + public ItemStack decrStackSize( int par1 ) + { + ItemStack is = super.decrStackSize( par1 ); + this.c.onCraftMatrixChanged( this.inventory ); + return is; + } } diff --git a/src/main/java/appeng/container/slot/SlotCraftingTerm.java b/src/main/java/appeng/container/slot/SlotCraftingTerm.java index 4fdd6c98e..d37649256 100644 --- a/src/main/java/appeng/container/slot/SlotCraftingTerm.java +++ b/src/main/java/appeng/container/slot/SlotCraftingTerm.java @@ -1,4 +1,3 @@ - /* * This file is part of Applied Energistics 2. * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. @@ -58,8 +57,7 @@ public class SlotCraftingTerm extends AppEngCraftingSlot private final IStorageMonitorable storage; private final IContainerCraftingPacket container; - public SlotCraftingTerm( EntityPlayer player, BaseActionSource mySrc, IEnergySource energySrc, IStorageMonitorable storage, IInventory cMatrix, - IInventory secondMatrix, IInventory output, int x, int y, IContainerCraftingPacket ccp ) + public SlotCraftingTerm( EntityPlayer player, BaseActionSource mySrc, IEnergySource energySrc, IStorageMonitorable storage, IInventory cMatrix, IInventory secondMatrix, IInventory output, int x, int y, IContainerCraftingPacket ccp ) { super( player, cMatrix, output, 0, x, y ); this.energySrc = energySrc; @@ -83,11 +81,67 @@ public class SlotCraftingTerm extends AppEngCraftingSlot @Override public void onPickupFromSlot( EntityPlayer p, ItemStack is ) - {} - - public void makeItem( EntityPlayer p, ItemStack is ) { - super.onPickupFromSlot( p, is ); + } + + public void doClick( InventoryAction action, EntityPlayer who ) + { + if( this.getStack() == null ) + return; + if( Platform.isClient() ) + return; + + IMEMonitor inv = this.storage.getItemInventory(); + int howManyPerCraft = this.getStack().stackSize; + int maxTimesToCraft = 0; + + InventoryAdaptor ia = null; + if( action == InventoryAction.CRAFT_SHIFT ) // craft into player inventory... + { + ia = InventoryAdaptor.getAdaptor( who, null ); + maxTimesToCraft = (int) Math.floor( (double) this.getStack().getMaxStackSize() / (double) howManyPerCraft ); + } + else if( action == InventoryAction.CRAFT_STACK ) // craft into hand, full stack + { + ia = new AdaptorPlayerHand( who ); + maxTimesToCraft = (int) Math.floor( (double) this.getStack().getMaxStackSize() / (double) howManyPerCraft ); + } + else + // pick up what was crafted... + { + ia = new AdaptorPlayerHand( who ); + maxTimesToCraft = 1; + } + + maxTimesToCraft = this.CapCraftingAttempts( maxTimesToCraft ); + + if( ia == null ) + return; + + ItemStack rs = Platform.cloneItemStack( this.getStack() ); + if( rs == null ) + return; + + for( int x = 0; x < maxTimesToCraft; x++ ) + { + if( ia.simulateAdd( rs ) == null ) + { + IItemList all = inv.getStorageList(); + ItemStack extra = ia.addItems( this.craftItem( who, rs, inv, all ) ); + if( extra != null ) + { + List drops = new ArrayList(); + drops.add( extra ); + Platform.spawnDrops( who.worldObj, (int) who.posX, (int) who.posY, (int) who.posZ, drops ); + return; + } + } + } + } + + protected int CapCraftingAttempts( int maxTimesToCraft ) + { + return maxTimesToCraft; } public ItemStack craftItem( EntityPlayer p, ItemStack request, IMEMonitor inv, IItemList all ) @@ -95,34 +149,34 @@ public class SlotCraftingTerm extends AppEngCraftingSlot // update crafting matrix... ItemStack is = this.getStack(); - if ( is != null && Platform.isSameItem( request, is ) ) + if( is != null && Platform.isSameItem( request, is ) ) { ItemStack[] set = new ItemStack[this.pattern.getSizeInventory()]; // add one of each item to the items on the board... - if ( Platform.isServer() ) + if( Platform.isServer() ) { InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for ( int x = 0; x < 9; x++ ) + for( int x = 0; x < 9; x++ ) ic.setInventorySlotContents( x, this.pattern.getStackInSlot( x ) ); IRecipe r = Platform.findMatchingRecipe( ic, p.worldObj ); - if ( r == null ) + if( r == null ) { Item target = request.getItem(); - if ( target.isDamageable() && target.isRepairable() ) + if( target.isDamageable() && target.isRepairable() ) { boolean isBad = false; - for ( int x = 0; x < ic.getSizeInventory(); x++ ) + for( int x = 0; x < ic.getSizeInventory(); x++ ) { ItemStack pis = ic.getStackInSlot( x ); - if ( pis == null ) + if( pis == null ) continue; - if ( pis.getItem() != target ) + if( pis.getItem() != target ) isBad = true; } - if ( !isBad ) + if( !isBad ) { super.onPickupFromSlot( p, is ); // actually necessary to cleanup this case... @@ -135,21 +189,20 @@ public class SlotCraftingTerm extends AppEngCraftingSlot is = r.getCraftingResult( ic ); - if ( inv != null ) + if( inv != null ) { - for ( int x = 0; x < this.pattern.getSizeInventory(); x++ ) + for( int x = 0; x < this.pattern.getSizeInventory(); x++ ) { - if ( this.pattern.getStackInSlot( x ) != null ) + if( this.pattern.getStackInSlot( x ) != null ) { - set[x] = Platform.extractItemsByRecipe( this.energySrc, this.mySrc, inv, p.worldObj, r, is, ic, this.pattern.getStackInSlot( x ), x, all, - Actionable.MODULATE, ItemViewCell.createFilter( this.container.getViewCells() ) ); + set[x] = Platform.extractItemsByRecipe( this.energySrc, this.mySrc, inv, p.worldObj, r, is, ic, this.pattern.getStackInSlot( x ), x, all, Actionable.MODULATE, ItemViewCell.createFilter( this.container.getViewCells() ) ); ic.setInventorySlotContents( x, set[x] ); } } } } - if ( this.preCraft( p, inv, set, is ) ) + if( this.preCraft( p, inv, set, is ) ) { this.makeItem( p, is ); @@ -170,92 +223,36 @@ public class SlotCraftingTerm extends AppEngCraftingSlot return true; } + public void makeItem( EntityPlayer p, ItemStack is ) + { + super.onPickupFromSlot( p, is ); + } + public void postCraft( EntityPlayer p, IMEMonitor inv, ItemStack[] set, ItemStack result ) { List drops = new ArrayList(); // add one of each item to the items on the board... - if ( Platform.isServer() ) + if( Platform.isServer() ) { // set new items onto the crafting table... - for ( int x = 0; x < this.craftInv.getSizeInventory(); x++ ) + for( int x = 0; x < this.craftInv.getSizeInventory(); x++ ) { - if ( this.craftInv.getStackInSlot( x ) == null ) + if( this.craftInv.getStackInSlot( x ) == null ) { this.craftInv.setInventorySlotContents( x, set[x] ); } - else if ( set[x] != null ) + else if( set[x] != null ) { // eek! put it back! IAEItemStack fail = inv.injectItems( AEItemStack.create( set[x] ), Actionable.MODULATE, this.mySrc ); - if ( fail != null ) + if( fail != null ) drops.add( fail.getItemStack() ); } } } - if ( drops.size() > 0 ) - Platform.spawnDrops( p.worldObj, ( int ) p.posX, ( int ) p.posY, ( int ) p.posZ, drops ); + if( drops.size() > 0 ) + Platform.spawnDrops( p.worldObj, (int) p.posX, (int) p.posY, (int) p.posZ, drops ); } - - public void doClick( InventoryAction action, EntityPlayer who ) - { - if ( this.getStack() == null ) - return; - if ( Platform.isClient() ) - return; - - IMEMonitor inv = this.storage.getItemInventory(); - int howManyPerCraft = this.getStack().stackSize; - int maxTimesToCraft = 0; - - InventoryAdaptor ia = null; - if ( action == InventoryAction.CRAFT_SHIFT ) // craft into player inventory... - { - ia = InventoryAdaptor.getAdaptor( who, null ); - maxTimesToCraft = ( int ) Math.floor( ( double ) this.getStack().getMaxStackSize() / ( double ) howManyPerCraft ); - } - else if ( action == InventoryAction.CRAFT_STACK ) // craft into hand, full stack - { - ia = new AdaptorPlayerHand( who ); - maxTimesToCraft = ( int ) Math.floor( ( double ) this.getStack().getMaxStackSize() / ( double ) howManyPerCraft ); - } - else - // pick up what was crafted... - { - ia = new AdaptorPlayerHand( who ); - maxTimesToCraft = 1; - } - - maxTimesToCraft = this.CapCraftingAttempts( maxTimesToCraft ); - - if ( ia == null ) - return; - - ItemStack rs = Platform.cloneItemStack( this.getStack() ); - if ( rs == null ) - return; - - for ( int x = 0; x < maxTimesToCraft; x++ ) - { - if ( ia.simulateAdd( rs ) == null ) - { - IItemList all = inv.getStorageList(); - ItemStack extra = ia.addItems( this.craftItem( who, rs, inv, all ) ); - if ( extra != null ) - { - List drops = new ArrayList(); - drops.add( extra ); - Platform.spawnDrops( who.worldObj, ( int ) who.posX, ( int ) who.posY, ( int ) who.posZ, drops ); - return; - } - } - } - } - - protected int CapCraftingAttempts( int maxTimesToCraft ) - { - return maxTimesToCraft; - } - } diff --git a/src/main/java/appeng/container/slot/SlotDisabled.java b/src/main/java/appeng/container/slot/SlotDisabled.java index 81c0cb7a0..a5121a169 100644 --- a/src/main/java/appeng/container/slot/SlotDisabled.java +++ b/src/main/java/appeng/container/slot/SlotDisabled.java @@ -18,25 +18,28 @@ package appeng.container.slot; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class SlotDisabled extends AppEngSlot { - public SlotDisabled(IInventory par1iInventory, int slotIndex, int x, int y) { + public SlotDisabled( IInventory par1iInventory, int slotIndex, int x, int y ) + { super( par1iInventory, slotIndex, x, y ); } @Override - public boolean isItemValid(ItemStack par1ItemStack) + public boolean isItemValid( ItemStack par1ItemStack ) { return false; } @Override - public boolean canTakeStack(EntityPlayer par1EntityPlayer) + public boolean canTakeStack( EntityPlayer par1EntityPlayer ) { return false; } diff --git a/src/main/java/appeng/container/slot/SlotFake.java b/src/main/java/appeng/container/slot/SlotFake.java index 47ecd2f12..bf6667ec3 100644 --- a/src/main/java/appeng/container/slot/SlotFake.java +++ b/src/main/java/appeng/container/slot/SlotFake.java @@ -18,50 +18,52 @@ package appeng.container.slot; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class SlotFake extends AppEngSlot { final int invSlot; - public SlotFake(IInventory inv, int idx, int x, int y) { + public SlotFake( IInventory inv, int idx, int x, int y ) + { super( inv, idx, x, y ); this.invSlot = idx; } @Override - public boolean canTakeStack(EntityPlayer par1EntityPlayer) + public void onPickupFromSlot( EntityPlayer par1EntityPlayer, ItemStack par2ItemStack ) { - return false; } @Override - public ItemStack decrStackSize(int par1) + public ItemStack decrStackSize( int par1 ) { return null; } @Override - public void onPickupFromSlot(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack) + public boolean isItemValid( ItemStack par1ItemStack ) { + return false; } @Override - public void putStack(ItemStack is) + public void putStack( ItemStack is ) { - if ( is != null ) + if( is != null ) is = is.copy(); super.putStack( is ); } @Override - public boolean isItemValid(ItemStack par1ItemStack) + public boolean canTakeStack( EntityPlayer par1EntityPlayer ) { return false; } - } diff --git a/src/main/java/appeng/container/slot/SlotFakeBlacklist.java b/src/main/java/appeng/container/slot/SlotFakeBlacklist.java index bf8d86553..fd4251df9 100644 --- a/src/main/java/appeng/container/slot/SlotFakeBlacklist.java +++ b/src/main/java/appeng/container/slot/SlotFakeBlacklist.java @@ -18,19 +18,16 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; + public class SlotFakeBlacklist extends SlotFakeTypeOnly { - public SlotFakeBlacklist(IInventory inv, int idx, int x, int y) { - super( inv, idx, x, y ); - } - - @Override - public boolean renderIconWithItem() + public SlotFakeBlacklist( IInventory inv, int idx, int x, int y ) { - return true; + super( inv, idx, x, y ); } @Override @@ -39,14 +36,19 @@ public class SlotFakeBlacklist extends SlotFakeTypeOnly return 0.8f; } + @Override + public boolean renderIconWithItem() + { + return true; + } + @Override public int getIcon() { - if ( this.getHasStack() ) + if( this.getHasStack() ) { return this.getStack().stackSize > 0 ? 16 + 14 : 14; } return -1; } - } diff --git a/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java b/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java index 0513aadcb..10691a1f9 100644 --- a/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java +++ b/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java @@ -18,13 +18,15 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; + public class SlotFakeCraftingMatrix extends SlotFake { - public SlotFakeCraftingMatrix(IInventory inv, int idx, int x, int y) { + public SlotFakeCraftingMatrix( IInventory inv, int idx, int x, int y ) + { super( inv, idx, x, y ); } - } diff --git a/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java b/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java index 74b85df26..602ee81f2 100644 --- a/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java +++ b/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java @@ -18,25 +18,28 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class SlotFakeTypeOnly extends SlotFake { - public SlotFakeTypeOnly(IInventory inv, int idx, int x, int y) { + public SlotFakeTypeOnly( IInventory inv, int idx, int x, int y ) + { super( inv, idx, x, y ); } @Override - public void putStack(ItemStack is) + public void putStack( ItemStack is ) { - if ( is != null ) + if( is != null ) { is = is.copy(); - if ( is.stackSize > 1 ) + if( is.stackSize > 1 ) is.stackSize = 1; - else if ( is.stackSize < -1 ) + else if( is.stackSize < -1 ) is.stackSize = -1; } diff --git a/src/main/java/appeng/container/slot/SlotInaccessible.java b/src/main/java/appeng/container/slot/SlotInaccessible.java index 6668f6fbe..73a5dbbba 100644 --- a/src/main/java/appeng/container/slot/SlotInaccessible.java +++ b/src/main/java/appeng/container/slot/SlotInaccessible.java @@ -18,29 +18,26 @@ package appeng.container.slot; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class SlotInaccessible extends AppEngSlot { - public SlotInaccessible(IInventory i, int slotIdx, int x, int y) { + ItemStack dspStack = null; + + public SlotInaccessible( IInventory i, int slotIdx, int x, int y ) + { super( i, slotIdx, x, y ); } - ItemStack dspStack = null; - @Override - public ItemStack getDisplayStack() + public boolean isItemValid( ItemStack i ) { - if ( this.dspStack == null ) - { - ItemStack dsp = super.getDisplayStack(); - if ( dsp != null ) - this.dspStack = dsp.copy(); - } - return this.dspStack; + return false; } @Override @@ -51,15 +48,20 @@ public class SlotInaccessible extends AppEngSlot } @Override - public boolean canTakeStack(EntityPlayer par1EntityPlayer) + public boolean canTakeStack( EntityPlayer par1EntityPlayer ) { return false; } @Override - public boolean isItemValid(ItemStack i) + public ItemStack getDisplayStack() { - return false; + if( this.dspStack == null ) + { + ItemStack dsp = super.getDisplayStack(); + if( dsp != null ) + this.dspStack = dsp.copy(); + } + return this.dspStack; } - } diff --git a/src/main/java/appeng/container/slot/SlotInaccessibleHD.java b/src/main/java/appeng/container/slot/SlotInaccessibleHD.java index d1aa45f7f..ff66547bf 100644 --- a/src/main/java/appeng/container/slot/SlotInaccessibleHD.java +++ b/src/main/java/appeng/container/slot/SlotInaccessibleHD.java @@ -18,13 +18,15 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; + public class SlotInaccessibleHD extends SlotInaccessible { - public SlotInaccessibleHD(IInventory i, int slotIdx, int x, int y) { + public SlotInaccessibleHD( IInventory i, int slotIdx, int x, int y ) + { super( i, slotIdx, x, y ); } - } diff --git a/src/main/java/appeng/container/slot/SlotMACPattern.java b/src/main/java/appeng/container/slot/SlotMACPattern.java index 8a4d0e9c1..05cff8e05 100644 --- a/src/main/java/appeng/container/slot/SlotMACPattern.java +++ b/src/main/java/appeng/container/slot/SlotMACPattern.java @@ -18,25 +18,27 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import appeng.container.implementations.ContainerMAC; + public class SlotMACPattern extends AppEngSlot { final ContainerMAC mac; - public SlotMACPattern(ContainerMAC mac, IInventory i, int slotIdx, int x, int y) { + public SlotMACPattern( ContainerMAC mac, IInventory i, int slotIdx, int x, int y ) + { super( i, slotIdx, x, y ); this.mac = mac; } @Override - public boolean isItemValid(ItemStack i) + public boolean isItemValid( ItemStack i ) { return this.mac.isValidItemForSlot( this.getSlotIndex(), i ); } - } diff --git a/src/main/java/appeng/container/slot/SlotNormal.java b/src/main/java/appeng/container/slot/SlotNormal.java index 5a85c58ec..02a267313 100644 --- a/src/main/java/appeng/container/slot/SlotNormal.java +++ b/src/main/java/appeng/container/slot/SlotNormal.java @@ -18,13 +18,15 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; + public class SlotNormal extends AppEngSlot { - public SlotNormal(IInventory inv, int slot, int xPos, int yPos) { + public SlotNormal( IInventory inv, int slot, int xPos, int yPos ) + { super( inv, slot, xPos, yPos ); } - } diff --git a/src/main/java/appeng/container/slot/SlotOutput.java b/src/main/java/appeng/container/slot/SlotOutput.java index 30c8bb63f..30c0d4d1b 100644 --- a/src/main/java/appeng/container/slot/SlotOutput.java +++ b/src/main/java/appeng/container/slot/SlotOutput.java @@ -18,19 +18,22 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class SlotOutput extends AppEngSlot { - public SlotOutput(IInventory a, int b, int c, int d, int i) { + public SlotOutput( IInventory a, int b, int c, int d, int i ) + { super( a, b, c, d ); this.IIcon = i; } @Override - public boolean isItemValid(ItemStack i) + public boolean isItemValid( ItemStack i ) { return false; } diff --git a/src/main/java/appeng/container/slot/SlotPatternOutputs.java b/src/main/java/appeng/container/slot/SlotPatternOutputs.java index 2252b7339..59eef686d 100644 --- a/src/main/java/appeng/container/slot/SlotPatternOutputs.java +++ b/src/main/java/appeng/container/slot/SlotPatternOutputs.java @@ -18,12 +18,15 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; + public class SlotPatternOutputs extends OptionalSlotFake { - public SlotPatternOutputs(IInventory inv, IOptionalSlotHost containerBus, int idx, int x, int y, int offX, int offY, int groupNum) { + public SlotPatternOutputs( IInventory inv, IOptionalSlotHost containerBus, int idx, int x, int y, int offX, int offY, int groupNum ) + { super( inv, containerBus, idx, x, y, offX, offY, groupNum ); } diff --git a/src/main/java/appeng/container/slot/SlotPatternTerm.java b/src/main/java/appeng/container/slot/SlotPatternTerm.java index 8e147ce4f..39288d51a 100644 --- a/src/main/java/appeng/container/slot/SlotPatternTerm.java +++ b/src/main/java/appeng/container/slot/SlotPatternTerm.java @@ -18,6 +18,7 @@ package appeng.container.slot; + import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; @@ -32,28 +33,32 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.packets.PacketPatternSlot; import appeng.helpers.IContainerCraftingPacket; + public class SlotPatternTerm extends SlotCraftingTerm { final int groupNum; final IOptionalSlotHost host; - public SlotPatternTerm(EntityPlayer player, BaseActionSource mySrc, IEnergySource energySrc, IStorageMonitorable storage, IInventory cMatrix, - IInventory secondMatrix, IInventory output, int x, int y, IOptionalSlotHost h, int groupNumber, IContainerCraftingPacket c) + public SlotPatternTerm( EntityPlayer player, BaseActionSource mySrc, IEnergySource energySrc, IStorageMonitorable storage, IInventory cMatrix, IInventory secondMatrix, IInventory output, int x, int y, IOptionalSlotHost h, int groupNumber, IContainerCraftingPacket c ) { super( player, mySrc, energySrc, storage, cMatrix, secondMatrix, output, x, y, c ); this.host = h; this.groupNum = groupNumber; + } + public AppEngPacket getRequest( boolean shift ) throws IOException + { + return new PacketPatternSlot( this.pattern, AEApi.instance().storage().createItemStack( this.getStack() ), shift ); } @Override public ItemStack getStack() { - if ( !this.isEnabled() ) + if( !this.isEnabled() ) { - if ( this.getDisplayStack() != null ) + if( this.getDisplayStack() != null ) this.clearStack(); } @@ -63,15 +68,9 @@ public class SlotPatternTerm extends SlotCraftingTerm @Override public boolean isEnabled() { - if ( this.host == null ) + if( this.host == null ) return false; return this.host.isSlotEnabled( this.groupNum ); } - - public AppEngPacket getRequest(boolean shift) throws IOException - { - return new PacketPatternSlot( this.pattern, AEApi.instance().storage().createItemStack( this.getStack() ), shift ); - } - } diff --git a/src/main/java/appeng/container/slot/SlotPlayerHotBar.java b/src/main/java/appeng/container/slot/SlotPlayerHotBar.java index 29ef47895..b56309d3e 100644 --- a/src/main/java/appeng/container/slot/SlotPlayerHotBar.java +++ b/src/main/java/appeng/container/slot/SlotPlayerHotBar.java @@ -18,12 +18,15 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; + public class SlotPlayerHotBar extends AppEngSlot { - public SlotPlayerHotBar(IInventory par1iInventory, int par2, int par3, int par4) { + public SlotPlayerHotBar( IInventory par1iInventory, int par2, int par3, int par4 ) + { super( par1iInventory, par2, par3, par4 ); this.isPlayerSide = true; } diff --git a/src/main/java/appeng/container/slot/SlotPlayerInv.java b/src/main/java/appeng/container/slot/SlotPlayerInv.java index ae959da02..5fd366217 100644 --- a/src/main/java/appeng/container/slot/SlotPlayerInv.java +++ b/src/main/java/appeng/container/slot/SlotPlayerInv.java @@ -18,14 +18,17 @@ package appeng.container.slot; + import net.minecraft.inventory.IInventory; // there is nothing special about this slot, its simply used to represent the players inventory, vs a container slot. + public class SlotPlayerInv extends AppEngSlot { - public SlotPlayerInv(IInventory par1iInventory, int par2, int par3, int par4) { + public SlotPlayerInv( IInventory par1iInventory, int par2, int par3, int par4 ) + { super( par1iInventory, par2, par3, par4 ); this.isPlayerSide = true; diff --git a/src/main/java/appeng/container/slot/SlotRestrictedInput.java b/src/main/java/appeng/container/slot/SlotRestrictedInput.java index 81f35b0ad..a5425ba03 100644 --- a/src/main/java/appeng/container/slot/SlotRestrictedInput.java +++ b/src/main/java/appeng/container/slot/SlotRestrictedInput.java @@ -18,6 +18,7 @@ package appeng.container.slot; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; @@ -44,67 +45,17 @@ import appeng.items.misc.ItemEncodedPattern; import appeng.recipes.handlers.Inscribe; import appeng.util.Platform; + public class SlotRestrictedInput extends AppEngSlot { - public enum PlacableItemType - { - STORAGE_CELLS(15), ORE( 16 + 15), STORAGE_COMPONENT(3 * 16 + 15), - - ENCODABLE_ITEM(4 * 16 + 15), TRASH(5 * 16 + 15), VALID_ENCODED_PATTERN_W_OUTPUT(7 * 16 + 15), ENCODED_PATTERN_W_OUTPUT(7 * 16 + 15), - - ENCODED_CRAFTING_PATTERN(7 * 16 + 15), ENCODED_PATTERN(7 * 16 + 15), PATTERN(8 * 16 + 15), BLANK_PATTERN(8 * 16 + 15), POWERED_TOOL(9 * 16 + 15), - - RANGE_BOOSTER(6 * 16 + 15), QE_SINGULARITY(10 * 16 + 15), SPATIAL_STORAGE_CELLS(11 * 16 + 15), - - FUEL(12 * 16 + 15), UPGRADES(13 * 16 + 15), WORKBENCH_CELL(15), BIOMETRIC_CARD(14 * 16 + 15), VIEW_CELL(4 * 16 + 14), - - INSCRIBER_PLATE(2 * 16 + 14), INSCRIBER_INPUT(3 * 16 + 14), METAL_INGOTS(3 * 16 + 14); - - public final int IIcon; - - PlacableItemType( int o ) { - this.IIcon = o; - } - } - - @Override - public int getSlotStackLimit() - { - if ( this.stackLimit != -1 ) - return this.stackLimit; - return super.getSlotStackLimit(); - } - - public boolean isValid(ItemStack is, World theWorld) - { - if ( this.which == PlacableItemType.VALID_ENCODED_PATTERN_W_OUTPUT ) - { - ICraftingPatternDetails ap = is.getItem() instanceof ICraftingPatternItem ? ((ICraftingPatternItem) is.getItem()).getPatternForItem( is, theWorld ) - : null; - return ap != null; - } - return true; - } - public final PlacableItemType which; + private final InventoryPlayer p; public boolean allowEdit = true; public int stackLimit = -1; - private final InventoryPlayer p; - @Override - public boolean canTakeStack(EntityPlayer par1EntityPlayer) + public SlotRestrictedInput( PlacableItemType valid, IInventory i, int slotIndex, int x, int y, InventoryPlayer p ) { - return this.allowEdit; - } - - public Slot setStackLimit(int i) - { - this.stackLimit = i; - return this; - } - - public SlotRestrictedInput(PlacableItemType valid, IInventory i, int slotIndex, int x, int y, InventoryPlayer p) { super( i, slotIndex, x, y ); this.which = valid; this.IIcon = valid.IIcon; @@ -112,58 +63,66 @@ public class SlotRestrictedInput extends AppEngSlot } @Override - public ItemStack getDisplayStack() + public int getSlotStackLimit() { - if ( Platform.isClient() && (this.which == PlacableItemType.ENCODED_PATTERN) ) + if( this.stackLimit != -1 ) + return this.stackLimit; + return super.getSlotStackLimit(); + } + + public boolean isValid( ItemStack is, World theWorld ) + { + if( this.which == PlacableItemType.VALID_ENCODED_PATTERN_W_OUTPUT ) { - ItemStack is = super.getStack(); - if ( is != null && is.getItem() instanceof ItemEncodedPattern ) - { - ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - ItemStack out = iep.getOutput( is ); - if ( out != null ) - return out; - } + ICraftingPatternDetails ap = is.getItem() instanceof ICraftingPatternItem ? ( (ICraftingPatternItem) is.getItem() ).getPatternForItem( is, theWorld ) : null; + return ap != null; } - return super.getStack(); + return true; + } + + public Slot setStackLimit( int i ) + { + this.stackLimit = i; + return this; } @Override - public boolean isItemValid(ItemStack i) + public boolean isItemValid( ItemStack i ) { - if ( !this.myContainer.isValidForSlot( this, i ) ) + if( !this.myContainer.isValidForSlot( this, i ) ) return false; - if ( i == null ) + if( i == null ) return false; - if ( i.getItem() == null ) + if( i.getItem() == null ) return false; - if ( !this.inventory.isItemValidForSlot( this.getSlotIndex(), i ) ) + if( !this.inventory.isItemValidForSlot( this.getSlotIndex(), i ) ) return false; - if ( !this.allowEdit ) + if( !this.allowEdit ) return false; final IDefinitions definitions = AEApi.instance().definitions(); final IMaterials materials = definitions.materials(); final IItems items = definitions.items(); - switch (this.which) + switch( this.which ) { case ENCODED_CRAFTING_PATTERN: - if ( i.getItem() instanceof ICraftingPatternItem ) + if( i.getItem() instanceof ICraftingPatternItem ) { ICraftingPatternItem b = (ICraftingPatternItem) i.getItem(); ICraftingPatternDetails de = b.getPatternForItem( i, this.p.player.worldObj ); - if ( de != null ) + if( de != null ) return de.isCraftable(); } return false; case VALID_ENCODED_PATTERN_W_OUTPUT: case ENCODED_PATTERN_W_OUTPUT: - case ENCODED_PATTERN: { - if ( i.getItem() instanceof ICraftingPatternItem ) + case ENCODED_PATTERN: + { + if( i.getItem() instanceof ICraftingPatternItem ) return true; // ICraftingPatternDetails pattern = i.getItem() instanceof ICraftingPatternItem ? ((ICraftingPatternItem) // i.getItem()).getPatternForItem( i ) : null; @@ -174,19 +133,19 @@ public class SlotRestrictedInput extends AppEngSlot case PATTERN: - if ( i.getItem() instanceof ICraftingPatternItem ) + if( i.getItem() instanceof ICraftingPatternItem ) return true; return materials.blankPattern().isSameAs( i ); case INSCRIBER_PLATE: - if ( materials.namePress().isSameAs( i ) ) + if( materials.namePress().isSameAs( i ) ) { return true; } - for (ItemStack is : Inscribe.PLATES ) - if ( Platform.isSameItemPrecise( is, i ) ) + for( ItemStack is : Inscribe.PLATES ) + if( Platform.isSameItemPrecise( is, i ) ) return true; return false; @@ -217,15 +176,15 @@ public class SlotRestrictedInput extends AppEngSlot return materials.wirelessBooster().isSameAs( i ); case SPATIAL_STORAGE_CELLS: - return i.getItem() instanceof ISpatialStorageCell && ((ISpatialStorageCell) i.getItem()).isSpatialStorage( i ); + return i.getItem() instanceof ISpatialStorageCell && ( (ISpatialStorageCell) i.getItem() ).isSpatialStorage( i ); case STORAGE_CELLS: return AEApi.instance().registries().cell().isCellHandled( i ); case WORKBENCH_CELL: - return i.getItem() instanceof ICellWorkbenchItem && ((ICellWorkbenchItem) i.getItem()).isEditable( i ); + return i.getItem() instanceof ICellWorkbenchItem && ( (ICellWorkbenchItem) i.getItem() ).isEditable( i ); case STORAGE_COMPONENT: - return i.getItem() instanceof IStorageComponent && ((IStorageComponent) i.getItem()).isStorageComponent( i ); + return i.getItem() instanceof IStorageComponent && ( (IStorageComponent) i.getItem() ).isStorageComponent( i ); case TRASH: - if ( AEApi.instance().registries().cell().isCellHandled( i ) ) + if( AEApi.instance().registries().cell().isCellHandled( i ) ) return false; return !( i.getItem() instanceof IStorageComponent && ( (IStorageComponent) i.getItem() ).isStorageComponent( i ) ); @@ -234,7 +193,7 @@ public class SlotRestrictedInput extends AppEngSlot case BIOMETRIC_CARD: return i.getItem() instanceof IBiometricCard; case UPGRADES: - return i.getItem() instanceof IUpgradeModule && ((IUpgradeModule) i.getItem()).getType( i ) != null; + return i.getItem() instanceof IUpgradeModule && ( (IUpgradeModule) i.getItem() ).getType( i ) != null; default: break; } @@ -242,20 +201,65 @@ public class SlotRestrictedInput extends AppEngSlot return false; } - static public boolean isMetalIngot(ItemStack i) + @Override + public boolean canTakeStack( EntityPlayer par1EntityPlayer ) { - if ( Platform.isSameItemPrecise( i, new ItemStack( Items.iron_ingot ) ) ) + return this.allowEdit; + } + + @Override + public ItemStack getDisplayStack() + { + if( Platform.isClient() && ( this.which == PlacableItemType.ENCODED_PATTERN ) ) + { + ItemStack is = super.getStack(); + if( is != null && is.getItem() instanceof ItemEncodedPattern ) + { + ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + ItemStack out = iep.getOutput( is ); + if( out != null ) + return out; + } + } + return super.getStack(); + } + + static public boolean isMetalIngot( ItemStack i ) + { + if( Platform.isSameItemPrecise( i, new ItemStack( Items.iron_ingot ) ) ) return true; - for (String name : new String[] { "Copper", "Tin", "Obsidian", "Iron", "Lead", "Bronze", "Brass", "Nickel", "Aluminium" }) + for( String name : new String[] { "Copper", "Tin", "Obsidian", "Iron", "Lead", "Bronze", "Brass", "Nickel", "Aluminium" } ) { - for (ItemStack ingot : OreDictionary.getOres( "ingot" + name )) + for( ItemStack ingot : OreDictionary.getOres( "ingot" + name ) ) { - if ( Platform.isSameItemPrecise( i, ingot ) ) + if( Platform.isSameItemPrecise( i, ingot ) ) return true; } } return false; } + + public enum PlacableItemType + { + STORAGE_CELLS( 15 ), ORE( 16 + 15 ), STORAGE_COMPONENT( 3 * 16 + 15 ), + + ENCODABLE_ITEM( 4 * 16 + 15 ), TRASH( 5 * 16 + 15 ), VALID_ENCODED_PATTERN_W_OUTPUT( 7 * 16 + 15 ), ENCODED_PATTERN_W_OUTPUT( 7 * 16 + 15 ), + + ENCODED_CRAFTING_PATTERN( 7 * 16 + 15 ), ENCODED_PATTERN( 7 * 16 + 15 ), PATTERN( 8 * 16 + 15 ), BLANK_PATTERN( 8 * 16 + 15 ), POWERED_TOOL( 9 * 16 + 15 ), + + RANGE_BOOSTER( 6 * 16 + 15 ), QE_SINGULARITY( 10 * 16 + 15 ), SPATIAL_STORAGE_CELLS( 11 * 16 + 15 ), + + FUEL( 12 * 16 + 15 ), UPGRADES( 13 * 16 + 15 ), WORKBENCH_CELL( 15 ), BIOMETRIC_CARD( 14 * 16 + 15 ), VIEW_CELL( 4 * 16 + 14 ), + + INSCRIBER_PLATE( 2 * 16 + 14 ), INSCRIBER_INPUT( 3 * 16 + 14 ), METAL_INGOTS( 3 * 16 + 14 ); + + public final int IIcon; + + PlacableItemType( int o ) + { + this.IIcon = o; + } + } } diff --git a/src/main/java/appeng/core/AEConfig.java b/src/main/java/appeng/core/AEConfig.java index 75372ecf9..41f5fb767 100644 --- a/src/main/java/appeng/core/AEConfig.java +++ b/src/main/java/appeng/core/AEConfig.java @@ -48,75 +48,33 @@ import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; + public class AEConfig extends Configuration implements IConfigurableObject, IConfigManagerHost { - public static AEConfig instance; - public static final double TUNNEL_POWER_LOSS = 0.05; - public static final String VERSION = "@version@"; public static final String CHANNEL = "@aechannel@"; - public final static String PACKET_CHANNEL = "AE"; - + public static AEConfig instance; public final IConfigManager settings = new ConfigManager( this ); public final EnumSet featureFlags = EnumSet.noneOf( AEFeature.class ); - PowerUnits selectedPowerUnit = PowerUnits.AE; - + public final int[] craftByStacks = new int[] { 1, 10, 100, 1000 }; + public final int[] priorityByStacks = new int[] { 1, 10, 100, 1000 }; + public final int[] levelByStacks = new int[] { 1, 10, 100, 1000 }; + private final double WirelessHighWirelessCount = 64; + final private File configFile; public int storageBiomeID = -1; public int storageProviderID = -1; - public int formationPlaneEntityLimit = 128; - public float spawnChargedChance = 0.92f; public int quartzOresPerCluster = 4; public int quartzOresClusterAmount = 15; public int chargedChange = 4; public int minMeteoriteDistance = 707; public int minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; - - private double WirelessBaseCost = 8; - private double WirelessCostMultiplier = 1; - private final double WirelessHighWirelessCount = 64; - private double WirelessTerminalDrainMultiplier = 1; - - private double WirelessBaseRange = 16; - private double WirelessBoosterRangeMultiplier = 1; - private double WirelessBoosterExp = 1.5; - - public double wireless_getDrainRate(double range) - { - return this.WirelessTerminalDrainMultiplier * range; - } - - public double wireless_getMaxRange(int boosters) - { - return this.WirelessBaseRange + this.WirelessBoosterRangeMultiplier * Math.pow( boosters, this.WirelessBoosterExp ); - } - - public double wireless_getPowerDrain(int boosters) - { - return this.WirelessBaseCost + this.WirelessCostMultiplier * Math.pow( boosters, 1 + boosters / this.WirelessHighWirelessCount ); - } - - @Override - public Property get(String category, String key, String defaultValue, String comment, Property.Type type) - { - Property prop = super.get( category, key, defaultValue, comment, type ); - - if ( prop != null ) - { - if ( !category.equals( "Client" ) ) - prop.setRequiresMcRestart( true ); - } - - return prop; - } - public double spatialPowerExponent = 1.35; public double spatialPowerMultiplier = 1250.0; - public String[] grinderOres = { // Vanilla Items "Obsidian", "Ender", "EnderPearl", "Coal", "Iron", "Gold", "Charcoal", "NetherQuartz", @@ -126,105 +84,32 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon "CertusQuartz", "Wheat", "Fluix", // Other Mod Ores "Brass", "Platinum", "Nickel", "Invar", "Aluminium", "Electrum", "Osmium", "Zinc" }; - public double oreDoublePercentage = 90.0; - public boolean enableEffects = true; public boolean useLargeFonts = false; public boolean useColoredCraftingStatus; - public final int[] craftByStacks = new int[] { 1, 10, 100, 1000 }; - public final int[] priorityByStacks = new int[] { 1, 10, 100, 1000 }; - public final int[] levelByStacks = new int[] { 1, 10, 100, 1000 }; - public int wirelessTerminalBattery = 1600000; public int entropyManipulatorBattery = 200000; public int matterCannonBattery = 200000; public int portableCellBattery = 20000; public int colorApplicatorBattery = 20000; public int chargedStaffBattery = 8000; - public boolean disableColoredCableRecipesInNEI = true; - public boolean updatable = false; - final private File configFile; - public double meteoriteClusterChance = 0.1; public double meteoriteSpawnChance = 0.3; public int[] meteoriteDimensionWhitelist = new int[] { 0 }; - public int craftingCalculationTimePerTick = 5; + PowerUnits selectedPowerUnit = PowerUnits.AE; + private double WirelessBaseCost = 8; + private double WirelessCostMultiplier = 1; + private double WirelessTerminalDrainMultiplier = 1; + private double WirelessBaseRange = 16; + private double WirelessBoosterRangeMultiplier = 1; + private double WirelessBoosterExp = 1.5; - - @SubscribeEvent - public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent eventArgs) + public AEConfig( File configFile ) { - if ( eventArgs.modID.equals( AppEng.MOD_ID ) ) - { - this.clientSync(); - } - } - - private void clientSync() - { - this.disableColoredCableRecipesInNEI = this.get( "Client", "disableColoredCableRecipesInNEI", true ).getBoolean( true ); - this.enableEffects = this.get( "Client", "enableEffects", true ).getBoolean( true ); - this.useLargeFonts = this.get( "Client", "useTerminalUseLargeFont", false ).getBoolean( false ); - this.useColoredCraftingStatus = this.get( "Client", "useColoredCraftingStatus", true ).getBoolean( true ); - - // load buttons.. - for (int btnNum = 0; btnNum < 4; btnNum++) - { - Property cmb = this.get( "Client", "craftAmtButton" + (btnNum + 1), this.craftByStacks[btnNum] ); - Property pmb = this.get( "Client", "priorityAmtButton" + (btnNum + 1), this.priorityByStacks[btnNum] ); - Property lmb = this.get( "Client", "levelAmtButton" + (btnNum + 1), this.levelByStacks[btnNum] ); - - int buttonCap = (int) (Math.pow( 10, btnNum + 1 ) - 1); - - this.craftByStacks[btnNum] = Math.abs( cmb.getInt( this.craftByStacks[btnNum] ) ); - this.priorityByStacks[btnNum] = Math.abs( pmb.getInt( this.priorityByStacks[btnNum] ) ); - this.levelByStacks[btnNum] = Math.abs( pmb.getInt( this.levelByStacks[btnNum] ) ); - - cmb.comment = "Controls buttons on Crafting Screen : Capped at " + buttonCap; - pmb.comment = "Controls buttons on Priority Screen : Capped at " + buttonCap; - lmb.comment = "Controls buttons on Level Emitter Screen : Capped at " + buttonCap; - - this.craftByStacks[btnNum] = Math.min( this.craftByStacks[btnNum], buttonCap ); - this.priorityByStacks[btnNum] = Math.min( this.priorityByStacks[btnNum], buttonCap ); - this.levelByStacks[btnNum] = Math.min( this.levelByStacks[btnNum], buttonCap ); - } - - for (Settings e : this.settings.getSettings()) - { - String Category = "Client"; // e.getClass().getSimpleName(); - Enum value = this.settings.getSetting( e ); - - Property p = this.get( Category, e.name(), value.name(), this.getListComment( value ) ); - - try - { - value = Enum.valueOf( value.getClass(), p.getString() ); - } - catch (IllegalArgumentException er) - { - AELog.info( "Invalid value '" + p.getString() + "' for " + e.name() + " using '" + value.name() + "' instead" ); - } - - this.settings.putSetting( e, value ); - } - - } - - public boolean disableColoredCableRecipesInNEI() - { - return this.disableColoredCableRecipesInNEI; - } - - public String getFilePath() - { - return this.configFile.toString(); - } - - public AEConfig( File configFile ) { super( configFile ); this.configFile = configFile; @@ -253,29 +138,25 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon this.settings.registerSetting( Settings.TERMINAL_STYLE, TerminalStyle.TALL ); this.settings.registerSetting( Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH ); - this.spawnChargedChance = (float) (1.0 - this.get( "worldGen", "spawnChargedChance", 1.0 - this.spawnChargedChance ).getDouble( 1.0 - this.spawnChargedChance )); + this.spawnChargedChance = (float) ( 1.0 - this.get( "worldGen", "spawnChargedChance", 1.0 - this.spawnChargedChance ).getDouble( 1.0 - this.spawnChargedChance ) ); this.minMeteoriteDistance = this.get( "worldGen", "minMeteoriteDistance", this.minMeteoriteDistance ).getInt( this.minMeteoriteDistance ); this.meteoriteClusterChance = this.get( "worldGen", "meteoriteClusterChance", this.meteoriteClusterChance ).getDouble( this.meteoriteClusterChance ); this.meteoriteSpawnChance = this.get( "worldGen", "meteoriteSpawnChance", this.meteoriteSpawnChance ).getDouble( this.meteoriteSpawnChance ); - this.meteoriteDimensionWhitelist = this.get ("worldGen", "meteoriteDimensionWhitelist", this.meteoriteDimensionWhitelist).getIntList(); + this.meteoriteDimensionWhitelist = this.get( "worldGen", "meteoriteDimensionWhitelist", this.meteoriteDimensionWhitelist ).getIntList(); this.quartzOresPerCluster = this.get( "worldGen", "quartzOresPerCluster", this.quartzOresPerCluster ).getInt( this.quartzOresPerCluster ); this.quartzOresClusterAmount = this.get( "worldGen", "quartzOresClusterAmount", this.quartzOresClusterAmount ).getInt( this.quartzOresClusterAmount ); this.minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; - this.addCustomCategoryComment( - "wireless", - "Range= WirelessBaseRange + WirelessBoosterRangeMultiplier * Math.pow( boosters, WirelessBoosterExp )\nPowerDrain= WirelessBaseCost + WirelessCostMultiplier * Math.pow( boosters, 1 + boosters / WirelessHighWirelessCount )" ); + this.addCustomCategoryComment( "wireless", "Range= WirelessBaseRange + WirelessBoosterRangeMultiplier * Math.pow( boosters, WirelessBoosterExp )\nPowerDrain= WirelessBaseCost + WirelessCostMultiplier * Math.pow( boosters, 1 + boosters / WirelessHighWirelessCount )" ); this.WirelessBaseCost = this.get( "wireless", "WirelessBaseCost", this.WirelessBaseCost ).getDouble( this.WirelessBaseCost ); this.WirelessCostMultiplier = this.get( "wireless", "WirelessCostMultiplier", this.WirelessCostMultiplier ).getDouble( this.WirelessCostMultiplier ); this.WirelessBaseRange = this.get( "wireless", "WirelessBaseRange", this.WirelessBaseRange ).getDouble( this.WirelessBaseRange ); - this.WirelessBoosterRangeMultiplier = this.get( "wireless", "WirelessBoosterRangeMultiplier", this.WirelessBoosterRangeMultiplier ).getDouble( - this.WirelessBoosterRangeMultiplier ); + this.WirelessBoosterRangeMultiplier = this.get( "wireless", "WirelessBoosterRangeMultiplier", this.WirelessBoosterRangeMultiplier ).getDouble( this.WirelessBoosterRangeMultiplier ); this.WirelessBoosterExp = this.get( "wireless", "WirelessBoosterExp", this.WirelessBoosterExp ).getDouble( this.WirelessBoosterExp ); - this.WirelessTerminalDrainMultiplier = this.get( "wireless", "WirelessTerminalDrainMultiplier", this.WirelessTerminalDrainMultiplier ).getDouble( - this.WirelessTerminalDrainMultiplier ); + this.WirelessTerminalDrainMultiplier = this.get( "wireless", "WirelessTerminalDrainMultiplier", this.WirelessTerminalDrainMultiplier ).getDouble( this.WirelessTerminalDrainMultiplier ); this.formationPlaneEntityLimit = this.get( "automation", "formationPlaneEntityLimit", this.formationPlaneEntityLimit ).getInt( this.formationPlaneEntityLimit ); @@ -288,11 +169,11 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon this.clientSync(); - for (AEFeature feature : AEFeature.values()) + for( AEFeature feature : AEFeature.values() ) { - if ( feature.isVisible ) + if( feature.isVisible ) { - if ( this.get( "Features." + feature.category, feature.name(), feature.defaultValue ).getBoolean( feature.defaultValue ) ) + if( this.get( "Features." + feature.category, feature.name(), feature.defaultValue ).getBoolean( feature.defaultValue ) ) this.featureFlags.add( feature ); } else @@ -300,10 +181,10 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon } ModContainer imb = cpw.mods.fml.common.Loader.instance().getIndexedModList().get( "ImmibisCore" ); - if ( imb != null ) + if( imb != null ) { List version = Arrays.asList( "59.0.0", "59.0.1", "59.0.2" ); - if ( version.contains( imb.getVersion() ) ) + if( version.contains( imb.getVersion() ) ) this.featureFlags.remove( AEFeature.AlphaPass ); } @@ -311,17 +192,17 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon { this.selectedPowerUnit = PowerUnits.valueOf( this.get( "Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment( this.selectedPowerUnit ) ).getString() ); } - catch (Throwable t) + catch( Throwable t ) { this.selectedPowerUnit = PowerUnits.AE; } - for (TickRates tr : TickRates.values()) + for( TickRates tr : TickRates.values() ) { tr.Load( this ); } - if ( this.isFeatureEnabled( AEFeature.SpatialIO ) ) + if( this.isFeatureEnabled( AEFeature.SpatialIO ) ) { this.storageBiomeID = this.get( "spatialio", "storageBiomeID", this.storageBiomeID ).getInt( this.storageBiomeID ); this.storageProviderID = this.get( "spatialio", "storageProviderID", this.storageProviderID ).getInt( this.storageProviderID ); @@ -329,41 +210,75 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon this.spatialPowerExponent = this.get( "spatialio", "spatialPowerExponent", this.spatialPowerExponent ).getDouble( this.spatialPowerExponent ); } - if ( this.isFeatureEnabled( AEFeature.CraftingCPU ) ) + if( this.isFeatureEnabled( AEFeature.CraftingCPU ) ) { - this.craftingCalculationTimePerTick = this.get( "craftingCPU", "craftingCalculationTimePerTick", this.craftingCalculationTimePerTick ).getInt( - this.craftingCalculationTimePerTick ); + this.craftingCalculationTimePerTick = this.get( "craftingCPU", "craftingCalculationTimePerTick", this.craftingCalculationTimePerTick ).getInt( this.craftingCalculationTimePerTick ); } this.updatable = true; } - public boolean useAEVersion(MaterialType mt) + private void clientSync() { - if ( this.isFeatureEnabled( AEFeature.WebsiteRecipes ) ) - return true; + this.disableColoredCableRecipesInNEI = this.get( "Client", "disableColoredCableRecipesInNEI", true ).getBoolean( true ); + this.enableEffects = this.get( "Client", "enableEffects", true ).getBoolean( true ); + this.useLargeFonts = this.get( "Client", "useTerminalUseLargeFont", false ).getBoolean( false ); + this.useColoredCraftingStatus = this.get( "Client", "useColoredCraftingStatus", true ).getBoolean( true ); - this.setCategoryComment( - "OreCamouflage", - "AE2 Automatically uses alternative ores present in your instance of MC to blend better with its surroundings, if you prefer you can disable this selectively using these flags; Its important to note, that some if these items even if enabled may not be craftable in game because other items are overriding their recipes." ); - Property p = this.get( "OreCamouflage", mt.name(), true ); - p.comment = "OreDictionary Names: " + mt.getOreName(); + // load buttons.. + for( int btnNum = 0; btnNum < 4; btnNum++ ) + { + Property cmb = this.get( "Client", "craftAmtButton" + ( btnNum + 1 ), this.craftByStacks[btnNum] ); + Property pmb = this.get( "Client", "priorityAmtButton" + ( btnNum + 1 ), this.priorityByStacks[btnNum] ); + Property lmb = this.get( "Client", "levelAmtButton" + ( btnNum + 1 ), this.levelByStacks[btnNum] ); - return !p.getBoolean( true ); + int buttonCap = (int) ( Math.pow( 10, btnNum + 1 ) - 1 ); + + this.craftByStacks[btnNum] = Math.abs( cmb.getInt( this.craftByStacks[btnNum] ) ); + this.priorityByStacks[btnNum] = Math.abs( pmb.getInt( this.priorityByStacks[btnNum] ) ); + this.levelByStacks[btnNum] = Math.abs( pmb.getInt( this.levelByStacks[btnNum] ) ); + + cmb.comment = "Controls buttons on Crafting Screen : Capped at " + buttonCap; + pmb.comment = "Controls buttons on Priority Screen : Capped at " + buttonCap; + lmb.comment = "Controls buttons on Level Emitter Screen : Capped at " + buttonCap; + + this.craftByStacks[btnNum] = Math.min( this.craftByStacks[btnNum], buttonCap ); + this.priorityByStacks[btnNum] = Math.min( this.priorityByStacks[btnNum], buttonCap ); + this.levelByStacks[btnNum] = Math.min( this.levelByStacks[btnNum], buttonCap ); + } + + for( Settings e : this.settings.getSettings() ) + { + String Category = "Client"; // e.getClass().getSimpleName(); + Enum value = this.settings.getSetting( e ); + + Property p = this.get( Category, e.name(), value.name(), this.getListComment( value ) ); + + try + { + value = Enum.valueOf( value.getClass(), p.getString() ); + } + catch( IllegalArgumentException er ) + { + AELog.info( "Invalid value '" + p.getString() + "' for " + e.name() + " using '" + value.name() + "' instead" ); + } + + this.settings.putSetting( e, value ); + } } - private String getListComment(Enum value) + private String getListComment( Enum value ) { String comment = null; - if ( value != null ) + if( value != null ) { EnumSet set = EnumSet.allOf( value.getClass() ); - for (Object Oeg : set) + for( Object Oeg : set ) { Enum eg = (Enum) Oeg; - if ( comment == null ) + if( comment == null ) comment = "Possible Values: " + eg.name(); else comment += ", " + eg.name(); @@ -373,27 +288,44 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon return comment; } - @Override - public void updateSetting(IConfigManager manager, Enum setting, Enum newValue) + public boolean isFeatureEnabled( AEFeature f ) { - for (Settings e : this.settings.getSettings()) + return this.featureFlags.contains( f ); + } + + public double wireless_getDrainRate( double range ) + { + return this.WirelessTerminalDrainMultiplier * range; + } + + public double wireless_getMaxRange( int boosters ) + { + return this.WirelessBaseRange + this.WirelessBoosterRangeMultiplier * Math.pow( boosters, this.WirelessBoosterExp ); + } + + public double wireless_getPowerDrain( int boosters ) + { + return this.WirelessBaseCost + this.WirelessCostMultiplier * Math.pow( boosters, 1 + boosters / this.WirelessHighWirelessCount ); + } + + @Override + public Property get( String category, String key, String defaultValue, String comment, Property.Type type ) + { + Property prop = super.get( category, key, defaultValue, comment, type ); + + if( prop != null ) { - if ( e == setting ) - { - String Category = "Client"; - Property p = this.get( Category, e.name(), this.settings.getSetting( e ).name(), this.getListComment( newValue ) ); - p.set( newValue.name() ); - } + if( !category.equals( "Client" ) ) + prop.setRequiresMcRestart( true ); } - if ( this.updatable ) - this.save(); + return prop; } @Override public void save() { - if ( this.isFeatureEnabled( AEFeature.SpatialIO ) ) + if( this.isFeatureEnabled( AEFeature.SpatialIO ) ) { this.get( "spatialio", "storageBiomeID", this.storageBiomeID ).set( this.storageBiomeID ); this.get( "spatialio", "storageProviderID", this.storageProviderID ).set( this.storageProviderID ); @@ -401,28 +333,81 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon this.get( "Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment( this.selectedPowerUnit ) ).set( this.selectedPowerUnit.name() ); - if ( this.hasChanged() ) + if( this.hasChanged() ) super.save(); } - public int getFreeIDSLot(int varID, String Category) + @SubscribeEvent + public void onConfigChanged( ConfigChangedEvent.OnConfigChangedEvent eventArgs ) + { + if( eventArgs.modID.equals( AppEng.MOD_ID ) ) + { + this.clientSync(); + } + } + + public boolean disableColoredCableRecipesInNEI() + { + return this.disableColoredCableRecipesInNEI; + } + + public String getFilePath() + { + return this.configFile.toString(); + } + + public boolean useAEVersion( MaterialType mt ) + { + if( this.isFeatureEnabled( AEFeature.WebsiteRecipes ) ) + return true; + + this.setCategoryComment( "OreCamouflage", "AE2 Automatically uses alternative ores present in your instance of MC to blend better with its surroundings, if you prefer you can disable this selectively using these flags; Its important to note, that some if these items even if enabled may not be craftable in game because other items are overriding their recipes." ); + Property p = this.get( "OreCamouflage", mt.name(), true ); + p.comment = "OreDictionary Names: " + mt.getOreName(); + + return !p.getBoolean( true ); + } + + @Override + public void updateSetting( IConfigManager manager, Enum setting, Enum newValue ) + { + for( Settings e : this.settings.getSettings() ) + { + if( e == setting ) + { + String Category = "Client"; + Property p = this.get( Category, e.name(), this.settings.getSetting( e ).name(), this.getListComment( newValue ) ); + p.set( newValue.name() ); + } + } + + if( this.updatable ) + this.save(); + } + + public int getFreeMaterial( int varID ) + { + return this.getFreeIDSLot( varID, "materials" ); + } + + public int getFreeIDSLot( int varID, String Category ) { boolean alreadyUsed = false; int min = 0; - for (Property p : this.getCategory( Category ).getValues().values()) + for( Property p : this.getCategory( Category ).getValues().values() ) { int thisInt = p.getInt(); - if ( varID == thisInt ) + if( varID == thisInt ) alreadyUsed = true; min = Math.max( min, thisInt + 1 ); } - if ( alreadyUsed ) + if( alreadyUsed ) { - if ( min < 16383 ) + if( min < 16383 ) min = 16383; return min; @@ -431,12 +416,7 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon return varID; } - public int getFreeMaterial(int varID) - { - return this.getFreeIDSLot( varID, "materials" ); - } - - public int getFreePart(int varID) + public int getFreePart( int varID ) { return this.getFreeIDSLot( varID, "parts" ); } @@ -447,32 +427,27 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon return this.settings; } - public boolean isFeatureEnabled(AEFeature f) - { - return this.featureFlags.contains( f ); - } - public boolean useTerminalUseLargeFont() { return this.useLargeFonts; } - public int craftItemsByStackAmounts(int i) + public int craftItemsByStackAmounts( int i ) { return this.craftByStacks[i]; } - public int priorityByStacksAmounts(int i) + public int priorityByStacksAmounts( int i ) { return this.priorityByStacks[i]; } - public int levelByStackAmounts(int i) + public int levelByStackAmounts( int i ) { return this.levelByStacks[i]; } - public Enum getSetting(String Category, Class class1, Enum myDefault) + public Enum getSetting( String Category, Class class1, Enum myDefault ) { String name = class1.getSimpleName(); Property p = this.get( Category, name, myDefault.name() ); @@ -481,7 +456,7 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon { return (Enum) class1.getField( p.toString() ).get( class1 ); } - catch (Throwable t) + catch( Throwable t ) { // :{ } @@ -489,7 +464,7 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon return myDefault; } - public void setSetting(String Category, Enum s) + public void setSetting( String Category, Enum s ) { String name = s.getClass().getSimpleName(); this.get( Category, name, s.name() ).set( s.name() ); @@ -501,10 +476,9 @@ public class AEConfig extends Configuration implements IConfigurableObject, ICon return this.selectedPowerUnit; } - public void nextPowerUnit(boolean backwards) + public void nextPowerUnit( boolean backwards ) { this.selectedPowerUnit = Platform.rotateEnum( this.selectedPowerUnit, backwards, Settings.POWER_UNITS.getPossibleValues() ); this.save(); } - } diff --git a/src/main/java/appeng/core/AELog.java b/src/main/java/appeng/core/AELog.java index 525d6065b..b9d1e2ed8 100644 --- a/src/main/java/appeng/core/AELog.java +++ b/src/main/java/appeng/core/AELog.java @@ -18,6 +18,7 @@ package appeng.core; + import org.apache.logging.log4j.Level; import cpw.mods.fml.relauncher.FMLRelaunchLog; @@ -26,76 +27,77 @@ import appeng.core.features.AEFeature; import appeng.tile.AEBaseTile; import appeng.util.Platform; + public final class AELog { public static final FMLRelaunchLog INSTANCE = FMLRelaunchLog.log; - private AELog() { - } - - private static void log(Level level, String format, Object... data) + private AELog() { - if ( AEConfig.instance == null || AEConfig.instance.isFeatureEnabled( AEFeature.Logging ) ) - { - FMLRelaunchLog.log( "AE2:" + (Platform.isServer() ? "S" : "C"), level, format, data ); - } } - public static void severe(String format, Object... data) - { - log( Level.ERROR, format, data ); - } - - public static void warning(String format, Object... data) + public static void warning( String format, Object... data ) { log( Level.WARN, format, data ); } - public static void info(String format, Object... data) + private static void log( Level level, String format, Object... data ) { - log( Level.INFO, format, data ); + if( AEConfig.instance == null || AEConfig.instance.isFeatureEnabled( AEFeature.Logging ) ) + { + FMLRelaunchLog.log( "AE2:" + ( Platform.isServer() ? "S" : "C" ), level, format, data ); + } } - public static void grinder(String o) + public static void grinder( String o ) { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.GrinderLogging ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.GrinderLogging ) ) { log( Level.DEBUG, "grinder: " + o ); } } - public static void error(Throwable e) + public static void integration( Throwable exception ) { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.Logging ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.IntegrationLogging ) ) + { + error( exception ); + } + } + + public static void error( Throwable e ) + { + if( AEConfig.instance.isFeatureEnabled( AEFeature.Logging ) ) { severe( "Error: " + e.getClass().getName() + " : " + e.getMessage() ); e.printStackTrace(); } } - public static void integration(Throwable exception) + public static void severe( String format, Object... data ) { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.IntegrationLogging ) ) - { - error( exception ); - } + log( Level.ERROR, format, data ); } - public static void blockUpdate(int xCoord, int yCoord, int zCoord, AEBaseTile aeBaseTile) + public static void blockUpdate( int xCoord, int yCoord, int zCoord, AEBaseTile aeBaseTile ) { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.UpdateLogging ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.UpdateLogging ) ) { info( aeBaseTile.getClass().getName() + " @ " + xCoord + ", " + yCoord + ", " + zCoord ); } } - public static void crafting(String format, Object... data) + public static void info( String format, Object... data ) { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.CraftingLog ) ) + log( Level.INFO, format, data ); + } + + public static void crafting( String format, Object... data ) + { + if( AEConfig.instance.isFeatureEnabled( AEFeature.CraftingLog ) ) { log( Level.INFO, format, data ); } } - } diff --git a/src/main/java/appeng/core/Api.java b/src/main/java/appeng/core/Api.java index 4f87f2084..f1032abf7 100644 --- a/src/main/java/appeng/core/Api.java +++ b/src/main/java/appeng/core/Api.java @@ -40,6 +40,7 @@ import appeng.me.GridConnection; import appeng.me.GridNode; import appeng.util.Platform; + public final class Api implements IAppEngApi { public static final Api INSTANCE = new Api(); @@ -118,7 +119,7 @@ public final class Api implements IAppEngApi @Override public IGridNode createGridNode( IGridBlock blk ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) throw new RuntimeException( "Grid Features are Server Side Only." ); return new GridNode( blk ); } diff --git a/src/main/java/appeng/core/AppEng.java b/src/main/java/appeng/core/AppEng.java index 530721091..64e1c420b 100644 --- a/src/main/java/appeng/core/AppEng.java +++ b/src/main/java/appeng/core/AppEng.java @@ -101,15 +101,15 @@ public class AppEng @EventHandler void preInit( FMLPreInitializationEvent event ) { - if ( !Loader.isModLoaded( "appliedenergistics2-core" ) ) + if( !Loader.isModLoaded( "appliedenergistics2-core" ) ) { CommonHelper.proxy.missingCoreMod(); } Stopwatch watch = Stopwatch.createStarted(); - this.configDirectory = new File(event.getModConfigurationDirectory().getPath(), "AppliedEnergistics2"); + this.configDirectory = new File( event.getModConfigurationDirectory().getPath(), "AppliedEnergistics2" ); - final File configFile = new File( this.configDirectory, "AppliedEnergistics2.cfg"); + final File configFile = new File( this.configDirectory, "AppliedEnergistics2.cfg" ); final File facadeFile = new File( this.configDirectory, "Facades.cfg" ); final File versionFile = new File( this.configDirectory, "VersionChecker.cfg" ); @@ -120,15 +120,15 @@ public class AppEng AELog.info( "Pre Initialization ( started )" ); CreativeTab.init(); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.Facades ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.Facades ) ) CreativeTabFacade.init(); - if ( Platform.isClient() ) + if( Platform.isClient() ) CommonHelper.proxy.init(); Registration.INSTANCE.preInitialize( event ); - if ( versionCheckerConfig.isEnabled() ) + if( versionCheckerConfig.isEnabled() ) { final VersionChecker versionChecker = new VersionChecker( versionCheckerConfig ); final Thread versionCheckerThread = new Thread( versionChecker ); diff --git a/src/main/java/appeng/core/CommonHelper.java b/src/main/java/appeng/core/CommonHelper.java index c2c76985c..7ed38b099 100644 --- a/src/main/java/appeng/core/CommonHelper.java +++ b/src/main/java/appeng/core/CommonHelper.java @@ -18,6 +18,7 @@ package appeng.core; + import java.util.List; import java.util.Random; @@ -33,29 +34,30 @@ import appeng.block.AEBaseBlock; import appeng.client.EffectType; import appeng.core.sync.AppEngPacket; + public abstract class CommonHelper { - @SidedProxy(clientSide = "appeng.client.ClientHelper", serverSide = "appeng.server.ServerHelper") + @SidedProxy( clientSide = "appeng.client.ClientHelper", serverSide = "appeng.server.ServerHelper" ) public static CommonHelper proxy; public abstract void init(); public abstract World getWorld(); - public abstract void bindTileEntitySpecialRenderer(Class tile, AEBaseBlock blk); + public abstract void bindTileEntitySpecialRenderer( Class tile, AEBaseBlock blk ); public abstract List getPlayers(); - public abstract void sendToAllNearExcept(EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet); + public abstract void sendToAllNearExcept( EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet ); - public abstract void spawnEffect(EffectType effect, World worldObj, double posX, double posY, double posZ, Object extra); + public abstract void spawnEffect( EffectType effect, World worldObj, double posX, double posY, double posZ, Object extra ); - public abstract boolean shouldAddParticles(Random r); + public abstract boolean shouldAddParticles( Random r ); public abstract MovingObjectPosition getMOP(); - public abstract void doRenderItem(ItemStack itemstack, World w); + public abstract void doRenderItem( ItemStack itemstack, World w ); public abstract void postInit(); @@ -63,8 +65,7 @@ public abstract class CommonHelper public abstract void triggerUpdates(); - public abstract void updateRenderMode(EntityPlayer player); + public abstract void updateRenderMode( EntityPlayer player ); public abstract void missingCoreMod(); - } diff --git a/src/main/java/appeng/core/CreativeTab.java b/src/main/java/appeng/core/CreativeTab.java index 419e95d0e..cd5d4bd82 100644 --- a/src/main/java/appeng/core/CreativeTab.java +++ b/src/main/java/appeng/core/CreativeTab.java @@ -65,9 +65,9 @@ public final class CreativeTab extends CreativeTabs private ItemStack findFirst( IItemDefinition... choices ) { - for ( IItemDefinition definition : choices ) + for( IItemDefinition definition : choices ) { - for ( ItemStack definitionStack : definition.maybeStack( 1 ).asSet() ) + for( ItemStack definitionStack : definition.maybeStack( 1 ).asSet() ) { return definitionStack; } diff --git a/src/main/java/appeng/core/CreativeTabFacade.java b/src/main/java/appeng/core/CreativeTabFacade.java index 031bf5d43..8546e16ce 100644 --- a/src/main/java/appeng/core/CreativeTabFacade.java +++ b/src/main/java/appeng/core/CreativeTabFacade.java @@ -18,6 +18,7 @@ package appeng.core; + import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.Item; @@ -28,15 +29,22 @@ import com.google.common.base.Optional; import appeng.api.AEApi; import appeng.items.parts.ItemFacade; + public final class CreativeTabFacade extends CreativeTabs { public static CreativeTabFacade instance = null; - public CreativeTabFacade() { + public CreativeTabFacade() + { super( "appliedenergistics2.facades" ); } + public static void init() + { + instance = new CreativeTabFacade(); + } + @Override public Item getTabIconItem() { @@ -47,17 +55,11 @@ public final class CreativeTabFacade extends CreativeTabs public ItemStack getIconItemStack() { final Optional maybeFacade = AEApi.instance().definitions().items().facade().maybeItem(); - if ( maybeFacade.isPresent() ) + if( maybeFacade.isPresent() ) { - return ((ItemFacade) maybeFacade.get()).getCreativeTabIcon(); + return ( (ItemFacade) maybeFacade.get() ).getCreativeTabIcon(); } return new ItemStack( Blocks.planks ); } - - public static void init() - { - instance = new CreativeTabFacade(); - } - } \ No newline at end of file diff --git a/src/main/java/appeng/core/FacadeConfig.java b/src/main/java/appeng/core/FacadeConfig.java index a2025f8e7..662689f36 100644 --- a/src/main/java/appeng/core/FacadeConfig.java +++ b/src/main/java/appeng/core/FacadeConfig.java @@ -18,6 +18,7 @@ package appeng.core; + import java.io.File; import java.lang.reflect.Field; import java.util.regex.Matcher; @@ -29,33 +30,35 @@ import net.minecraftforge.common.config.Configuration; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; + public class FacadeConfig extends Configuration { public static FacadeConfig instance; final Pattern replacementPattern; - public FacadeConfig( File facadeFile ) { + public FacadeConfig( File facadeFile ) + { super( facadeFile ); this.replacementPattern = Pattern.compile( "[^a-zA-Z0-9]" ); } - public boolean checkEnabled(Block id, int metadata, boolean automatic) + public boolean checkEnabled( Block id, int metadata, boolean automatic ) { - if ( id == null ) + if( id == null ) return false; UniqueIdentifier blk = GameRegistry.findUniqueIdentifierFor( id ); - if ( blk == null ) + if( blk == null ) { - for (Field f : Block.class.getFields()) + for( Field f : Block.class.getFields() ) { try { - if ( f.get( Block.class ) == id ) - return this.get( "minecraft", f.getName() + (metadata == 0 ? "" : "." + metadata), automatic ).getBoolean( automatic ); + if( f.get( Block.class ) == id ) + return this.get( "minecraft", f.getName() + ( metadata == 0 ? "" : "." + metadata ), automatic ).getBoolean( automatic ); } - catch (Throwable e) + catch( Throwable e ) { // :P } @@ -65,7 +68,7 @@ public class FacadeConfig extends Configuration { Matcher mod = this.replacementPattern.matcher( blk.modId ); Matcher name = this.replacementPattern.matcher( blk.name ); - return this.get( mod.replaceAll( "" ), name.replaceAll( "" ) + (metadata == 0 ? "" : "." + metadata), automatic ).getBoolean( automatic ); + return this.get( mod.replaceAll( "" ), name.replaceAll( "" ) + ( metadata == 0 ? "" : "." + metadata ), automatic ).getBoolean( automatic ); } return false; diff --git a/src/main/java/appeng/core/IMCHandler.java b/src/main/java/appeng/core/IMCHandler.java index 5325584f4..5fae71a26 100644 --- a/src/main/java/appeng/core/IMCHandler.java +++ b/src/main/java/appeng/core/IMCHandler.java @@ -58,7 +58,7 @@ public class IMCHandler this.processors.put( "add-grindable", new IMCGrinder() ); this.processors.put( "add-mattercannon-ammo", new IMCMatterCannon() ); - for ( TunnelType type : TunnelType.values() ) + for( TunnelType type : TunnelType.values() ) { this.processors.put( "add-p2p-attunement-" + type.name().replace( '_', '-' ).toLowerCase(), new IMCP2PAttunement() ); } @@ -72,14 +72,14 @@ public class IMCHandler */ public void handleIMCEvent( FMLInterModComms.IMCEvent event ) { - for ( FMLInterModComms.IMCMessage message : event.getMessages() ) + for( FMLInterModComms.IMCMessage message : event.getMessages() ) { final String key = message.key; try { IIMCProcessor handler = this.processors.get( key ); - if ( handler != null ) + if( handler != null ) { handler.process( message ); } @@ -88,7 +88,7 @@ public class IMCHandler throw new RuntimeException( "Invalid IMC Called: " + key ); } } - catch ( Throwable t ) + catch( Throwable t ) { AELog.warning( "Problem detected when processing IMC " + key + " from " + message.getSender() ); AELog.error( t ); diff --git a/src/main/java/appeng/core/PlayerMappings.java b/src/main/java/appeng/core/PlayerMappings.java index 9dc96bd04..b1f3c1e3d 100644 --- a/src/main/java/appeng/core/PlayerMappings.java +++ b/src/main/java/appeng/core/PlayerMappings.java @@ -22,12 +22,12 @@ package appeng.core; import java.util.Map; import java.util.UUID; -import com.google.common.base.Optional; - import net.minecraftforge.common.config.ConfigCategory; import cpw.mods.fml.relauncher.FMLRelaunchLog; +import com.google.common.base.Optional; + /** * Wrapper class for the player mappings. diff --git a/src/main/java/appeng/core/PlayerMappingsInitializer.java b/src/main/java/appeng/core/PlayerMappingsInitializer.java index c54840423..97cbf8f5e 100644 --- a/src/main/java/appeng/core/PlayerMappingsInitializer.java +++ b/src/main/java/appeng/core/PlayerMappingsInitializer.java @@ -64,12 +64,12 @@ public class PlayerMappingsInitializer this.playerMappings = new HashMap( capacity ); // Iterates through every pair of UUID to ID - for ( Map.Entry entry : playerList.getValues().entrySet() ) + for( Map.Entry entry : playerList.getValues().entrySet() ) { final String maybeUUID = entry.getKey(); final int id = entry.getValue().getInt(); - if ( matcher.isUUID( maybeUUID ) ) + if( matcher.isUUID( maybeUUID ) ) { final UUID UUIDString = UUID.fromString( maybeUUID ); diff --git a/src/main/java/appeng/core/Registration.java b/src/main/java/appeng/core/Registration.java index 2ac4e7667..6b3f8b878 100644 --- a/src/main/java/appeng/core/Registration.java +++ b/src/main/java/appeng/core/Registration.java @@ -76,8 +76,6 @@ import appeng.core.localization.GuiText; import appeng.core.localization.PlayerMessages; import appeng.core.stats.PlayerStatsRegistration; import appeng.hooks.AETrading; -import appeng.worldgen.MeteoriteWorldGen; -import appeng.worldgen.QuartzWorldGen; import appeng.hooks.TickHandler; import appeng.integration.IntegrationType; import appeng.items.materials.ItemMultiMaterial; @@ -117,6 +115,8 @@ import appeng.spatial.BiomeGenStorage; import appeng.spatial.StorageWorldProvider; import appeng.tile.AEBaseTile; import appeng.util.Platform; +import appeng.worldgen.MeteoriteWorldGen; +import appeng.worldgen.QuartzWorldGen; public final class Registration @@ -165,12 +165,12 @@ public final class Registration this.assignItems( items, apiItems ); // Register all detected handlers and features (items, blocks) in pre-init - for ( IFeatureHandler handler : definitions.getFeatureHandlerRegistry().getRegisteredFeatureHandlers() ) + for( IFeatureHandler handler : definitions.getFeatureHandlerRegistry().getRegisteredFeatureHandlers() ) { handler.register(); } - for ( IAEFeature feature : definitions.getFeatureRegistry().getRegisteredFeatures() ) + for( IAEFeature feature : definitions.getFeatureRegistry().getRegisteredFeatures() ) { feature.postInit(); } @@ -178,37 +178,37 @@ public final class Registration private void registerSpatial( boolean force ) { - if ( !AEConfig.instance.isFeatureEnabled( AEFeature.SpatialIO ) ) + if( !AEConfig.instance.isFeatureEnabled( AEFeature.SpatialIO ) ) return; AEConfig config = AEConfig.instance; - if ( this.storageBiome == null ) + if( this.storageBiome == null ) { - if ( force && config.storageBiomeID == -1 ) + if( force && config.storageBiomeID == -1 ) { config.storageBiomeID = Platform.findEmpty( BiomeGenBase.getBiomeGenArray() ); - if ( config.storageBiomeID == -1 ) + if( config.storageBiomeID == -1 ) throw new RuntimeException( "Biome Array is full, please free up some Biome ID's or disable spatial." ); this.storageBiome = new BiomeGenStorage( config.storageBiomeID ); config.save(); } - if ( !force && config.storageBiomeID != -1 ) + if( !force && config.storageBiomeID != -1 ) this.storageBiome = new BiomeGenStorage( config.storageBiomeID ); } - if ( config.storageProviderID != -1 ) + if( config.storageProviderID != -1 ) { DimensionManager.registerProviderType( config.storageProviderID, StorageWorldProvider.class, false ); } - if ( config.storageProviderID == -1 && force ) + if( config.storageProviderID == -1 && force ) { config.storageProviderID = -11; - while ( !DimensionManager.registerProviderType( config.storageProviderID, StorageWorldProvider.class, false ) ) + while( !DimensionManager.registerProviderType( config.storageProviderID, StorageWorldProvider.class, false ) ) config.storageProviderID--; config.save(); @@ -508,7 +508,7 @@ public final class Registration // Perform ore camouflage! ItemMultiMaterial.instance.makeUnique(); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.CustomRecipes ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.CustomRecipes ) ) this.recipeHandler.parseRecipes( new ConfigLoader( AppEng.instance.getConfigDirectory() ), "index.recipe" ); else this.recipeHandler.parseRecipes( new JarLoader( "/assets/appliedenergistics2/recipes/" ), "index.recipe" ); @@ -517,13 +517,13 @@ public final class Registration partHelper.registerNewLayer( "appeng.parts.layers.LayerIFluidHandler", "net.minecraftforge.fluids.IFluidHandler" ); partHelper.registerNewLayer( "appeng.parts.layers.LayerITileStorageMonitorable", "appeng.api.implementations.tiles.ITileStorageMonitorable" ); - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.IC2 ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.IC2 ) ) { partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergySink", "ic2.api.energy.tile.IEnergySink" ); partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergySource", "ic2.api.energy.tile.IEnergySource" ); } - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.RF ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.RF ) ) partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergyHandler", "cofh.api.energy.IEnergyReceiver" ); FMLCommonHandler.instance().bus().register( TickHandler.INSTANCE ); @@ -548,7 +548,7 @@ public final class Registration registries.cell().addCellHandler( new BasicCellHandler() ); registries.cell().addCellHandler( new CreativeCellHandler() ); - for ( ItemStack ammoStack : api.definitions().materials().matterBall().maybeStack( 1 ).asSet() ) + for( ItemStack ammoStack : api.definitions().materials().matterBall().maybeStack( 1 ).asSet() ) { final double weight = 32; @@ -561,10 +561,10 @@ public final class Registration registration.registerAchievementHandlers(); registration.registerAchievements(); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.enableDisassemblyCrafting ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.enableDisassemblyCrafting ) ) CraftingManager.getInstance().getRecipeList().add( new DisassembleRecipe() ); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.enableFacadeCrafting ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.enableFacadeCrafting ) ) CraftingManager.getInstance().getRecipeList().add( new FacadeRecipe() ); } @@ -587,7 +587,7 @@ public final class Registration GuiText.values(); Api.INSTANCE.getPartHelper().initFMPSupport(); - for ( Block block : blocks.multiPart().maybeBlock().asSet() ) + for( Block block : blocks.multiPart().maybeBlock().asSet() ) { ( (BlockCableBus) block ).setupTile(); } @@ -657,35 +657,35 @@ public final class Registration // Inscriber Upgrades.SPEED.registerItem( blocks.inscriber(), 3 ); - for ( Item wirelessTerminalItem : items.wirelessTerminal().maybeItem().asSet() ) + for( Item wirelessTerminalItem : items.wirelessTerminal().maybeItem().asSet() ) { registries.wireless().registerWirelessHandler( (IWirelessTermHandler) wirelessTerminalItem ); } - if ( AEConfig.instance.isFeatureEnabled( AEFeature.ChestLoot ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.ChestLoot ) ) { ChestGenHooks d = ChestGenHooks.getInfo( ChestGenHooks.MINESHAFT_CORRIDOR ); final IMaterials materials = definitions.materials(); - for ( ItemStack crystal : materials.certusQuartzCrystal().maybeStack( 1 ).asSet() ) + for( ItemStack crystal : materials.certusQuartzCrystal().maybeStack( 1 ).asSet() ) { d.addItem( new WeightedRandomChestContent( crystal, 1, 4, 2 ) ); } - for ( ItemStack dust : materials.certusQuartzDust().maybeStack( 1 ).asSet() ) + for( ItemStack dust : materials.certusQuartzDust().maybeStack( 1 ).asSet() ) { d.addItem( new WeightedRandomChestContent( dust, 1, 4, 2 ) ); } } // add villager trading to black smiths for a few basic materials - if ( AEConfig.instance.isFeatureEnabled( AEFeature.VillagerTrading ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.VillagerTrading ) ) VillagerRegistry.instance().registerVillageTradeHandler( 3, new AETrading() ); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzWorldGen ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzWorldGen ) ) GameRegistry.registerWorldGenerator( new QuartzWorldGen(), 0 ); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.MeteoriteWorldGen ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.MeteoriteWorldGen ) ) { GameRegistry.registerWorldGenerator( new MeteoriteWorldGen(), 0 ); } @@ -728,7 +728,7 @@ public final class Registration /** * world gen */ - for ( WorldGenType type : WorldGenType.values() ) + for( WorldGenType type : WorldGenType.values() ) { registries.worldgen().disableWorldGenForProviderID( type, StorageWorldProvider.class ); @@ -740,7 +740,7 @@ public final class Registration } // whitelist from config - for ( int dimension : AEConfig.instance.meteoriteDimensionWhitelist ) + for( int dimension : AEConfig.instance.meteoriteDimensionWhitelist ) { registries.worldgen().enableWorldGenForDimension( WorldGenType.Meteorites, dimension ); } diff --git a/src/main/java/appeng/core/WorldSettings.java b/src/main/java/appeng/core/WorldSettings.java index b484a1e73..07c5a1f4c 100644 --- a/src/main/java/appeng/core/WorldSettings.java +++ b/src/main/java/appeng/core/WorldSettings.java @@ -74,7 +74,7 @@ public class WorldSettings extends Configuration this.spawnDataFolder = new File( aeFolder, SPAWNDATA_FOLDER ); this.compass = new CompassService( aeFolder ); - for ( int dimID : this.get( "DimensionManager", "StorageCells", new int[0] ).getIntList() ) + for( int dimID : this.get( "DimensionManager", "StorageCells", new int[0] ).getIntList() ) { this.storageCellDims.add( dimID ); DimensionManager.registerDimension( dimID, AEConfig.instance.storageProviderID ); @@ -85,7 +85,7 @@ public class WorldSettings extends Configuration this.lastGridStorage = Long.parseLong( this.get( "Counters", "lastGridStorage", 0 ).getString() ); this.lastPlayer = this.get( "Counters", "lastPlayer", 0 ).getInt(); } - catch ( NumberFormatException err ) + catch( NumberFormatException err ) { this.lastGridStorage = 0; this.lastPlayer = 0; @@ -97,25 +97,25 @@ public class WorldSettings extends Configuration public static WorldSettings getInstance() { - if ( instance == null ) + if( instance == null ) { File world = DimensionManager.getCurrentSaveRootDirectory(); File aeBaseFolder = new File( world.getPath(), "AE2" ); - if ( !aeBaseFolder.isDirectory() && !aeBaseFolder.mkdir() ) + if( !aeBaseFolder.isDirectory() && !aeBaseFolder.mkdir() ) { throw new RuntimeException( "Failed to create " + aeBaseFolder.getAbsolutePath() ); } File compass = new File( aeBaseFolder, COMPASS_FOLDER ); - if ( !compass.isDirectory() && !compass.mkdir() ) + if( !compass.isDirectory() && !compass.mkdir() ) { throw new RuntimeException( "Failed to create " + compass.getAbsolutePath() ); } File spawnData = new File( aeBaseFolder, SPAWNDATA_FOLDER ); - if ( !spawnData.isDirectory() && !spawnData.mkdir() ) + if( !spawnData.isDirectory() && !spawnData.mkdir() ) { throw new RuntimeException( "Failed to create " + spawnData.getAbsolutePath() ); } @@ -130,22 +130,22 @@ public class WorldSettings extends Configuration { Collection ll = new LinkedList(); - synchronized ( WorldSettings.class ) + synchronized( WorldSettings.class ) { - for ( int x = -1; x <= 1; x++ ) + for( int x = -1; x <= 1; x++ ) { - for ( int z = -1; z <= 1; z++ ) + for( int z = -1; z <= 1; z++ ) { int cx = x + ( chunkX >> 4 ); int cz = z + ( chunkZ >> 4 ); NBTTagCompound data = this.loadSpawnData( dim, cx << 4, cz << 4 ); - if ( data != null ) + if( data != null ) { // edit. int size = data.getInteger( "num" ); - for ( int s = 0; s < size; s++ ) + for( int s = 0; s < size; s++ ) ll.add( data.getCompoundTag( String.valueOf( s ) ) ); } } @@ -157,13 +157,13 @@ public class WorldSettings extends Configuration NBTTagCompound loadSpawnData( int dim, int chunkX, int chunkZ ) { - if ( !Thread.holdsLock( WorldSettings.class ) ) + if( !Thread.holdsLock( WorldSettings.class ) ) throw new RuntimeException( "Invalid Request" ); NBTTagCompound data = null; File file = new File( this.spawnDataFolder, dim + '_' + ( chunkX >> 4 ) + '_' + ( chunkZ >> 4 ) + ".dat" ); - if ( file.isFile() ) + if( file.isFile() ) { FileInputStream fileInputStream = null; @@ -172,20 +172,20 @@ public class WorldSettings extends Configuration fileInputStream = new FileInputStream( file ); data = CompressedStreamTools.readCompressed( fileInputStream ); } - catch ( Throwable e ) + catch( Throwable e ) { data = new NBTTagCompound(); AELog.error( e ); } finally { - if ( fileInputStream != null ) + if( fileInputStream != null ) { try { fileInputStream.close(); } - catch ( IOException e ) + catch( IOException e ) { AELog.error( e ); } @@ -202,7 +202,7 @@ public class WorldSettings extends Configuration public boolean hasGenerated( int dim, int chunkX, int chunkZ ) { - synchronized ( WorldSettings.class ) + synchronized( WorldSettings.class ) { NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); return data.getBoolean( chunkX + "," + chunkZ ); @@ -211,7 +211,7 @@ public class WorldSettings extends Configuration public void setGenerated( int dim, int chunkX, int chunkZ ) { - synchronized ( WorldSettings.class ) + synchronized( WorldSettings.class ) { NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); @@ -224,7 +224,7 @@ public class WorldSettings extends Configuration void writeSpawnData( int dim, int chunkX, int chunkZ, NBTTagCompound data ) { - if ( !Thread.holdsLock( WorldSettings.class ) ) + if( !Thread.holdsLock( WorldSettings.class ) ) throw new RuntimeException( "Invalid Request" ); File file = new File( this.spawnDataFolder, dim + '_' + ( chunkX >> 4 ) + '_' + ( chunkZ >> 4 ) + ".dat" ); @@ -235,19 +235,19 @@ public class WorldSettings extends Configuration fileOutputStream = new FileOutputStream( file ); CompressedStreamTools.writeCompressed( data, fileOutputStream ); } - catch ( Throwable e ) + catch( Throwable e ) { AELog.error( e ); } finally { - if ( fileOutputStream != null ) + if( fileOutputStream != null ) { try { fileOutputStream.close(); } - catch ( IOException e ) + catch( IOException e ) { AELog.error( e ); } @@ -257,7 +257,7 @@ public class WorldSettings extends Configuration public boolean addNearByMeteorites( int dim, int chunkX, int chunkZ, NBTTagCompound newData ) { - synchronized ( WorldSettings.class ) + synchronized( WorldSettings.class ) { NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); @@ -276,7 +276,7 @@ public class WorldSettings extends Configuration { this.save(); - for ( Integer dimID : this.storageCellDims ) + for( Integer dimID : this.storageCellDims ) DimensionManager.unregisterDimension( dimID ); this.storageCellDims.clear(); @@ -289,10 +289,10 @@ public class WorldSettings extends Configuration public void save() { // populate new data - for ( GridStorageSearch gs : this.loadedStorage.keySet() ) + for( GridStorageSearch gs : this.loadedStorage.keySet() ) { GridStorage thisStorage = gs.gridStorage.get(); - if ( thisStorage != null && thisStorage.getGrid() != null && !thisStorage.getGrid().isEmpty() ) + if( thisStorage != null && thisStorage.getGrid() != null && !thisStorage.getGrid().isEmpty() ) { String value = thisStorage.getValue(); this.get( "gridstorage", String.valueOf( thisStorage.getID() ), value ).set( value ); @@ -300,7 +300,7 @@ public class WorldSettings extends Configuration } // save to files - if ( this.hasChanged() ) + if( this.hasChanged() ) super.save(); } @@ -313,7 +313,7 @@ public class WorldSettings extends Configuration String[] values = new String[this.storageCellDims.size()]; - for ( int x = 0; x < values.length; x++ ) + for( int x = 0; x < values.length; x++ ) values[x] = String.valueOf( this.storageCellDims.get( x ) ); this.get( "DimensionManager", "StorageCells", new int[0] ).set( values ); @@ -327,16 +327,16 @@ public class WorldSettings extends Configuration public void sendToPlayer( NetworkManager manager ) { - if ( manager != null ) + if( manager != null ) { - for ( int newDim : this.get( "DimensionManager", "StorageCells", new int[0] ).getIntList() ) + for( int newDim : this.get( "DimensionManager", "StorageCells", new int[0] ).getIntList() ) { manager.scheduleOutboundPacket( ( new PacketNewStorageDimension( newDim ) ).getProxy() ); } } else { - for ( PlayerColor pc : TickHandler.INSTANCE.getPlayerColors().values() ) + for( PlayerColor pc : TickHandler.INSTANCE.getPlayerColors().values() ) NetworkHandler.instance.sendToAll( pc.getPacket() ); } } @@ -374,7 +374,7 @@ public class WorldSettings extends Configuration GridStorageSearch gss = new GridStorageSearch( storageID ); WeakReference result = this.loadedStorage.get( gss ); - if ( result == null || result.get() == null ) + if( result == null || result.get() == null ) { String id = String.valueOf( storageID ); String Data = this.get( "gridstorage", id, "" ).getString(); @@ -426,13 +426,13 @@ public class WorldSettings extends Configuration { ConfigCategory playerList = this.getCategory( "players" ); - if ( playerList == null || profile == null || !profile.isComplete() ) + if( playerList == null || profile == null || !profile.isComplete() ) return -1; String uuid = profile.getId().toString(); Property prop = playerList.get( uuid ); - if ( prop != null && prop.isIntValue() ) + if( prop != null && prop.isIntValue() ) return prop.getInt(); else { @@ -455,12 +455,12 @@ public class WorldSettings extends Configuration { Optional maybe = this.mappings.get( playerID ); - if ( maybe.isPresent() ) + if( maybe.isPresent() ) { final UUID uuid = maybe.get(); - for ( EntityPlayer player : CommonHelper.proxy.getPlayers() ) + for( EntityPlayer player : CommonHelper.proxy.getPlayers() ) { - if ( player.getUniqueID().equals( uuid ) ) + if( player.getUniqueID().equals( uuid ) ) return player; } } diff --git a/src/main/java/appeng/core/api/ApiPart.java b/src/main/java/appeng/core/api/ApiPart.java index 871da7888..b1383024b 100644 --- a/src/main/java/appeng/core/api/ApiPart.java +++ b/src/main/java/appeng/core/api/ApiPart.java @@ -27,8 +27,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; -import com.google.common.base.Joiner; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.commons.Remapper; @@ -45,6 +43,8 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; +import com.google.common.base.Joiner; + import appeng.api.parts.CableRenderMode; import appeng.api.parts.IPartHelper; import appeng.api.parts.IPartItem; @@ -59,6 +59,7 @@ import appeng.parts.PartPlacement; import appeng.tile.networking.TileCableBus; import appeng.util.Platform; + public class ApiPart implements IPartHelper { @@ -69,14 +70,212 @@ public class ApiPart implements IPartHelper public void initFMPSupport() { - for (Class layerInterface : this.interfaces2Layer.keySet()) + for( Class layerInterface : this.interfaces2Layer.keySet() ) { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) - ((IFMP) AppEng.instance.getIntegration( IntegrationType.FMP )).registerPassThrough( layerInterface ); + if( AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) + ( (IFMP) AppEng.instance.getIntegration( IntegrationType.FMP ) ).registerPassThrough( layerInterface ); } } - private Class loadClass(String Name, byte[] b) + public Class getCombinedInstance( String base ) + { + if( this.desc.size() == 0 ) + { + try + { + return Class.forName( base ); + } + catch( Throwable t ) + { + throw new RuntimeException( t ); + } + } + + String description = base + ':' + Joiner.on( ";" ).skipNulls().join( this.desc.iterator() ); + + if( this.tileImplementations.get( description ) != null ) + { + try + { + return this.tileImplementations.get( description ); + } + catch( Throwable t ) + { + throw new RuntimeException( t ); + } + } + + String f = base;// TileCableBus.class.getName(); + String Addendum = ""; + try + { + Addendum = Class.forName( base ).getSimpleName(); + } + catch( ClassNotFoundException e ) + { + AELog.error( e ); + } + Class myCLass; + + try + { + myCLass = Class.forName( f ); + } + catch( Throwable t ) + { + throw new RuntimeException( t ); + } + + String path = f; + + for( String name : this.desc ) + { + try + { + String newPath = path + ';' + name; + myCLass = this.getClassByDesc( Addendum, newPath, f, this.interfaces2Layer.get( Class.forName( name ) ) ); + path = newPath; + } + catch( Throwable t ) + { + AELog.warning( "Error loading " + name ); + AELog.error( t ); + // throw new RuntimeException( t ); + } + f = myCLass.getName(); + } + + this.tileImplementations.put( description, myCLass ); + + try + { + return myCLass; + } + catch( Throwable t ) + { + throw new RuntimeException( t ); + } + } + + public Class getClassByDesc( String Addendum, String fullPath, String root, String next ) + { + if( this.roots.get( fullPath ) != null ) + return this.roots.get( fullPath ); + + ClassWriter cw = new ClassWriter( ClassWriter.COMPUTE_MAXS ); + ClassNode n = this.getReader( next ); + String originalName = n.name; + + try + { + n.name = n.name + '_' + Addendum; + n.superName = Class.forName( root ).getName().replace( ".", "/" ); + } + catch( Throwable t ) + { + AELog.error( t ); + } + + for( MethodNode mn : n.methods ) + { + Iterator i = mn.instructions.iterator(); + while( i.hasNext() ) + { + this.processNode( i.next(), n.superName ); + } + } + + DefaultPackageClassNameRemapper remapper = new DefaultPackageClassNameRemapper(); + remapper.inputOutput.put( "appeng/api/parts/LayerBase", n.superName ); + remapper.inputOutput.put( originalName, n.name ); + n.accept( new RemappingClassAdapter( cw, remapper ) ); + // n.accept( cw ); + + // n.accept( new TraceClassVisitor( new PrintWriter( System.out ) ) ); + byte[] byteArray = cw.toByteArray(); + int size = byteArray.length; + Class clazz = this.loadClass( n.name.replace( "/", "." ), byteArray ); + + try + { + Object fish = clazz.newInstance(); + Class rootC = Class.forName( root ); + + boolean hasError = false; + + if( !rootC.isInstance( fish ) ) + { + hasError = true; + AELog.severe( "Error, Expected layer to implement " + root + " did not." ); + } + + if( fish instanceof LayerBase ) + { + hasError = true; + AELog.severe( "Error, Expected layer to NOT implement LayerBase but it DID." ); + } + + if( !fullPath.contains( ".fmp." ) ) + { + if( !( fish instanceof TileCableBus ) ) + { + hasError = true; + AELog.severe( "Error, Expected layer to implement TileCableBus did not." ); + } + + if( !( fish instanceof TileEntity ) ) + { + hasError = true; + AELog.severe( "Error, Expected layer to implement TileEntity did not." ); + } + } + + if( !hasError ) + { + AELog.info( "Layer: " + n.name + " loaded successfully - " + size + " bytes" ); + } + } + catch( Throwable t ) + { + AELog.severe( "Layer: " + n.name + " Failed." ); + AELog.error( t ); + } + + this.roots.put( fullPath, clazz ); + return clazz; + } + + public ClassNode getReader( String name ) + { + try + { + ClassReader cr; + String path = '/' + name.replace( ".", "/" ) + ".class"; + InputStream is = this.getClass().getResourceAsStream( path ); + cr = new ClassReader( is ); + ClassNode cn = new ClassNode(); + cr.accept( cn, ClassReader.EXPAND_FRAMES ); + return cn; + } + catch( Throwable t ) + { + throw new RuntimeException( "Error loading " + name, t ); + } + } + + private void processNode( AbstractInsnNode next, String nePar ) + { + if( next instanceof MethodInsnNode ) + { + MethodInsnNode min = (MethodInsnNode) next; + if( min.owner.equals( "appeng/api/parts/LayerBase" ) ) + { + min.owner = nePar; + } + } + } + + private Class loadClass( String Name, byte[] b ) { // override classDefine (as it is protected) and define the class. Class clazz = null; @@ -104,7 +303,7 @@ public class ApiPart implements IPartHelper defineClassMethod.setAccessible( false ); } } - catch (Exception e) + catch( Exception e ) { AELog.error( e ); throw new RuntimeException( "Unable to manage part API.", e ); @@ -112,241 +311,13 @@ public class ApiPart implements IPartHelper return clazz; } - public ClassNode getReader(String name) - { - try - { - ClassReader cr; - String path = '/' + name.replace( ".", "/" ) + ".class"; - InputStream is = this.getClass().getResourceAsStream( path ); - cr = new ClassReader( is ); - ClassNode cn = new ClassNode(); - cr.accept( cn, ClassReader.EXPAND_FRAMES ); - return cn; - } - catch (Throwable t) - { - throw new RuntimeException( "Error loading " + name, t ); - } - } - - public Class getCombinedInstance(String base) - { - if ( this.desc.size() == 0 ) - { - try - { - return Class.forName( base ); - } - catch (Throwable t) - { - throw new RuntimeException( t ); - } - } - - String description = base + ':' + Joiner.on( ";" ).skipNulls().join( this.desc.iterator() ); - - if ( this.tileImplementations.get( description ) != null ) - { - try - { - return this.tileImplementations.get( description ); - } - catch (Throwable t) - { - throw new RuntimeException( t ); - } - } - - String f = base;// TileCableBus.class.getName(); - String Addendum = ""; - try - { - Addendum = Class.forName( base ).getSimpleName(); - } - catch (ClassNotFoundException e) - { - AELog.error( e ); - } - Class myCLass; - - try - { - myCLass = Class.forName( f ); - } - catch (Throwable t) - { - throw new RuntimeException( t ); - } - - String path = f; - - for (String name : this.desc) - { - try - { - String newPath = path + ';' + name; - myCLass = this.getClassByDesc( Addendum, newPath, f, this.interfaces2Layer.get( Class.forName( name ) ) ); - path = newPath; - } - catch (Throwable t) - { - AELog.warning( "Error loading " + name ); - AELog.error( t ); - // throw new RuntimeException( t ); - } - f = myCLass.getName(); - } - - this.tileImplementations.put( description, myCLass ); - - try - { - return myCLass; - } - catch (Throwable t) - { - throw new RuntimeException( t ); - } - } - - static class DefaultPackageClassNameRemapper extends Remapper - { - - public final HashMap inputOutput = new HashMap(); - - @Override - public String map(String typeName) - { - String o = this.inputOutput.get( typeName ); - if ( o == null ) - return typeName; - return o; - } - - } - - public Class getClassByDesc(String Addendum, String fullPath, String root, String next) - { - if ( this.roots.get( fullPath ) != null ) - return this.roots.get( fullPath ); - - ClassWriter cw = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - ClassNode n = this.getReader( next ); - String originalName = n.name; - - try - { - n.name = n.name + '_' + Addendum; - n.superName = Class.forName( root ).getName().replace( ".", "/" ); - } - catch (Throwable t) - { - AELog.error( t ); - } - - for (MethodNode mn : n.methods) - { - Iterator i = mn.instructions.iterator(); - while (i.hasNext()) - { - this.processNode( i.next(), n.superName ); - } - } - - DefaultPackageClassNameRemapper remapper = new DefaultPackageClassNameRemapper(); - remapper.inputOutput.put( "appeng/api/parts/LayerBase", n.superName ); - remapper.inputOutput.put( originalName, n.name ); - n.accept( new RemappingClassAdapter( cw, remapper ) ); - // n.accept( cw ); - - // n.accept( new TraceClassVisitor( new PrintWriter( System.out ) ) ); - byte[] byteArray = cw.toByteArray(); - int size = byteArray.length; - Class clazz = this.loadClass( n.name.replace( "/", "." ), byteArray ); - - try - { - Object fish = clazz.newInstance(); - Class rootC = Class.forName( root ); - - boolean hasError = false; - - if ( !rootC.isInstance( fish ) ) - { - hasError = true; - AELog.severe( "Error, Expected layer to implement " + root + " did not." ); - } - - if ( fish instanceof LayerBase ) - { - hasError = true; - AELog.severe( "Error, Expected layer to NOT implement LayerBase but it DID." ); - } - - if ( !fullPath.contains( ".fmp." ) ) - { - if ( !(fish instanceof TileCableBus) ) - { - hasError = true; - AELog.severe( "Error, Expected layer to implement TileCableBus did not." ); - } - - if ( !(fish instanceof TileEntity) ) - { - hasError = true; - AELog.severe( "Error, Expected layer to implement TileEntity did not." ); - } - } - - if ( !hasError ) - { - AELog.info( "Layer: " + n.name + " loaded successfully - " + size + " bytes" ); - } - - } - catch (Throwable t) - { - AELog.severe( "Layer: " + n.name + " Failed." ); - AELog.error( t ); - } - - this.roots.put( fullPath, clazz ); - return clazz; - } - - private void processNode(AbstractInsnNode next, String nePar) - { - if ( next instanceof MethodInsnNode ) - { - MethodInsnNode min = (MethodInsnNode) next; - if ( min.owner.equals( "appeng/api/parts/LayerBase" ) ) - { - min.owner = nePar; - } - } - } - @Override - public void setItemBusRenderer(IPartItem i) - { - if ( Platform.isClient() && i instanceof Item ) - MinecraftForgeClient.registerItemRenderer( (Item) i, BusRenderer.INSTANCE ); - } - - @Override - public boolean placeBus(ItemStack is, int x, int y, int z, int side, EntityPlayer player, World w) - { - return PartPlacement.place( is, x, y, z, side, player, w, PartPlacement.PlaceType.PLACE_ITEM, 0 ); - } - - @Override - public boolean registerNewLayer(String layer, String layerInterface) + public boolean registerNewLayer( String layer, String layerInterface ) { try { final Class layerInterfaceClass = Class.forName( layerInterface ); - if ( this.interfaces2Layer.get( layerInterfaceClass ) == null ) + if( this.interfaces2Layer.get( layerInterfaceClass ) == null ) { this.interfaces2Layer.put( layerInterfaceClass, layer ); this.desc.add( layerInterface ); @@ -355,17 +326,44 @@ public class ApiPart implements IPartHelper else AELog.info( "Layer " + layer + " not registered, " + layerInterface + " already has a layer." ); } - catch (Throwable ignored) + catch( Throwable ignored ) { } return false; } + @Override + public void setItemBusRenderer( IPartItem i ) + { + if( Platform.isClient() && i instanceof Item ) + MinecraftForgeClient.registerItemRenderer( (Item) i, BusRenderer.INSTANCE ); + } + + @Override + public boolean placeBus( ItemStack is, int x, int y, int z, int side, EntityPlayer player, World w ) + { + return PartPlacement.place( is, x, y, z, side, player, w, PartPlacement.PlaceType.PLACE_ITEM, 0 ); + } + @Override public CableRenderMode getCableRenderMode() { return CommonHelper.proxy.getRenderMode(); } + static class DefaultPackageClassNameRemapper extends Remapper + { + + public final HashMap inputOutput = new HashMap(); + + @Override + public String map( String typeName ) + { + String o = this.inputOutput.get( typeName ); + if( o == null ) + return typeName; + return o; + } + } } diff --git a/src/main/java/appeng/core/api/ApiStorage.java b/src/main/java/appeng/core/api/ApiStorage.java index f784b7602..1d6936134 100644 --- a/src/main/java/appeng/core/api/ApiStorage.java +++ b/src/main/java/appeng/core/api/ApiStorage.java @@ -18,6 +18,7 @@ package appeng.core.api; + import java.io.IOException; import io.netty.buffer.ByteBuf; @@ -41,17 +42,24 @@ import appeng.util.item.AEFluidStack; import appeng.util.item.AEItemStack; import appeng.util.item.ItemList; + public class ApiStorage implements IStorageHelper { @Override - public IAEItemStack createItemStack(ItemStack is) + public ICraftingLink loadCraftingLink( NBTTagCompound data, ICraftingRequester req ) + { + return new CraftingLink( data, req ); + } + + @Override + public IAEItemStack createItemStack( ItemStack is ) { return AEItemStack.create( is ); } @Override - public IAEFluidStack createFluidStack(FluidStack is) + public IAEFluidStack createFluidStack( FluidStack is ) { return AEFluidStack.create( is ); } @@ -69,32 +77,26 @@ public class ApiStorage implements IStorageHelper } @Override - public IAEItemStack poweredExtraction(IEnergySource energy, IMEInventory cell, IAEItemStack request, BaseActionSource src) - { - return Platform.poweredExtraction( energy, cell, request, src ); - } - - @Override - public IAEItemStack poweredInsert(IEnergySource energy, IMEInventory cell, IAEItemStack input, BaseActionSource src) - { - return Platform.poweredInsert( energy, cell, input, src ); - } - - @Override - public IAEItemStack readItemFromPacket(ByteBuf input) throws IOException + public IAEItemStack readItemFromPacket( ByteBuf input ) throws IOException { return AEItemStack.loadItemStackFromPacket( input ); } @Override - public IAEFluidStack readFluidFromPacket(ByteBuf input) throws IOException + public IAEFluidStack readFluidFromPacket( ByteBuf input ) throws IOException { return AEFluidStack.loadFluidStackFromPacket( input ); } @Override - public ICraftingLink loadCraftingLink(NBTTagCompound data, ICraftingRequester req) + public IAEItemStack poweredExtraction( IEnergySource energy, IMEInventory cell, IAEItemStack request, BaseActionSource src ) { - return new CraftingLink( data, req ); + return Platform.poweredExtraction( energy, cell, request, src ); + } + + @Override + public IAEItemStack poweredInsert( IEnergySource energy, IMEInventory cell, IAEItemStack input, BaseActionSource src ) + { + return Platform.poweredInsert( energy, cell, input, src ); } } diff --git a/src/main/java/appeng/core/api/IIMCProcessor.java b/src/main/java/appeng/core/api/IIMCProcessor.java index 3b8a35690..47e0b55b0 100644 --- a/src/main/java/appeng/core/api/IIMCProcessor.java +++ b/src/main/java/appeng/core/api/IIMCProcessor.java @@ -18,8 +18,10 @@ package appeng.core.api; + import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; + public interface IIMCProcessor { void process( IMCMessage m ); diff --git a/src/main/java/appeng/core/api/definitions/ApiParts.java b/src/main/java/appeng/core/api/definitions/ApiParts.java index c8bea230a..3539ac954 100644 --- a/src/main/java/appeng/core/api/definitions/ApiParts.java +++ b/src/main/java/appeng/core/api/definitions/ApiParts.java @@ -38,10 +38,10 @@ public final class ApiParts implements IParts private final AEColoredItemDefinition cableCovered; private final AEColoredItemDefinition cableGlass; private final AEColoredItemDefinition cableDense; -// private final AEColoredItemDefinition lumenCableSmart; -// private final AEColoredItemDefinition lumenCableCovered; -// private final AEColoredItemDefinition lumenCableGlass; -// private final AEColoredItemDefinition lumenCableDense; + // private final AEColoredItemDefinition lumenCableSmart; + // private final AEColoredItemDefinition lumenCableCovered; + // private final AEColoredItemDefinition lumenCableGlass; + // private final AEColoredItemDefinition lumenCableDense; private final IItemDefinition quartzFiber; private final IItemDefinition toggleBus; private final IItemDefinition invertedToggleBus; @@ -79,10 +79,10 @@ public final class ApiParts implements IParts this.cableCovered = constructor.constructColoredDefinition( itemMultiPart, PartType.CableCovered ); this.cableGlass = constructor.constructColoredDefinition( itemMultiPart, PartType.CableGlass ); this.cableDense = constructor.constructColoredDefinition( itemMultiPart, PartType.CableDense ); -// this.lumenCableSmart = Optional.absent(); // has yet to be implemented, no PartType defined for it yet -// this.lumenCableCovered = Optional.absent(); // has yet to be implemented, no PartType defined for it yet -// this.lumenCableGlass = Optional.absent(); // has yet to be implemented, no PartType defined for it yet -// this.lumenCableDense = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableSmart = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableCovered = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableGlass = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableDense = Optional.absent(); // has yet to be implemented, no PartType defined for it yet this.quartzFiber = new DamagedItemDefinition( itemMultiPart.createPart( PartType.QuartzFiber ) ); this.toggleBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ToggleBus ) ); this.invertedToggleBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.InvertedToggleBus ) ); @@ -140,28 +140,28 @@ public final class ApiParts implements IParts public AEColoredItemDefinition lumenCableSmart() { throw new MissingDefinition( "Lumen Smart Cable has yet to be implemented." ); -// return this.lumenCableSmart; + // return this.lumenCableSmart; } @Override public AEColoredItemDefinition lumenCableCovered() { throw new MissingDefinition( "Lumen Covered Cable has yet to be implemented." ); -// return this.lumenCableCovered; + // return this.lumenCableCovered; } @Override public AEColoredItemDefinition lumenCableGlass() { throw new MissingDefinition( "Lumen Glass Cable has yet to be implemented." ); -// return this.lumenCableGlass; + // return this.lumenCableGlass; } @Override public AEColoredItemDefinition lumenCableDense() { throw new MissingDefinition( "Lumen Dense Cable has yet to be implemented." ); -// return this.lumenCableDense; + // return this.lumenCableDense; } @Override diff --git a/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java b/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java index 4a88c8155..0ae1d5ffb 100644 --- a/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java +++ b/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java @@ -35,7 +35,7 @@ public class DefinitionConstructor { final IBlockDefinition definition = this.registerBlockDefinition( feature ); - if ( definition instanceof ITileDefinition ) + if( definition instanceof ITileDefinition ) { return ( (ITileDefinition) definition ); } @@ -47,7 +47,7 @@ public class DefinitionConstructor { final IItemDefinition definition = this.registerItemDefinition( feature ); - if ( definition instanceof IBlockDefinition ) + if( definition instanceof IBlockDefinition ) { return ( (IBlockDefinition) definition ); } @@ -59,7 +59,7 @@ public class DefinitionConstructor { final IFeatureHandler handler = feature.handler(); - if ( handler.isFeatureAvailable() ) + if( handler.isFeatureAvailable() ) { this.handlers.addFeatureHandler( handler ); this.features.addFeature( feature ); @@ -74,9 +74,9 @@ public class DefinitionConstructor { final ColoredItemDefinition definition = new ColoredItemDefinition(); - for ( Item targetItem : target.maybeItem().asSet() ) + for( Item targetItem : target.maybeItem().asSet() ) { - for ( AEColor color : AEColor.VALID_COLORS ) + for( AEColor color : AEColor.VALID_COLORS ) { definition.add( color, new ItemStackSrc( targetItem, offset + color.ordinal() ) ); } @@ -89,12 +89,12 @@ public class DefinitionConstructor { final ColoredItemDefinition definition = new ColoredItemDefinition(); - for ( AEColor color : AEColor.values() ) + for( AEColor color : AEColor.values() ) { ItemStackSrc multiPartSource = target.createPart( type, color ); final Optional maybeSource = Optional.fromNullable( multiPartSource ); - if ( maybeSource.isPresent() ) + if( maybeSource.isPresent() ) { definition.add( color, multiPartSource ); } diff --git a/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java b/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java index ee78b9579..30663ddda 100644 --- a/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java +++ b/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java @@ -18,6 +18,7 @@ package appeng.core.api.imc; + import net.minecraft.block.Block; import net.minecraft.item.ItemStack; @@ -27,6 +28,7 @@ import appeng.api.AEApi; import appeng.core.AELog; import appeng.core.api.IIMCProcessor; + public class IMCBlackListSpatial implements IIMCProcessor { @@ -35,10 +37,10 @@ public class IMCBlackListSpatial implements IIMCProcessor { ItemStack is = m.getItemStackValue(); - if ( is != null ) + if( is != null ) { Block blk = Block.getBlockFromItem( is.getItem() ); - if ( blk != null ) + if( blk != null ) { AEApi.instance().registries().movable().blacklistBlock( blk ); return; @@ -46,7 +48,5 @@ public class IMCBlackListSpatial implements IIMCProcessor } AELog.info( "Bad Block blacklisted by " + m.getSender() ); - } - } diff --git a/src/main/java/appeng/core/api/imc/IMCGrinder.java b/src/main/java/appeng/core/api/imc/IMCGrinder.java index 779cfac42..2a902c78c 100644 --- a/src/main/java/appeng/core/api/imc/IMCGrinder.java +++ b/src/main/java/appeng/core/api/imc/IMCGrinder.java @@ -49,8 +49,10 @@ msg.setInteger( "turns", 8 ); FMLInterModComms.sendMessage( "appliedenergistics2", "add-grindable", msg ); */ + package appeng.core.api.imc; + import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -59,6 +61,7 @@ import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import appeng.api.AEApi; import appeng.core.api.IIMCProcessor; + public class IMCGrinder implements IIMCProcessor { @Override @@ -73,18 +76,18 @@ public class IMCGrinder implements IIMCProcessor int turns = msg.getInteger( "turns" ); - if ( in == null ) + if( in == null ) throw new RuntimeException( "invalid input" ); - if ( out == null ) + if( out == null ) throw new RuntimeException( "invalid output" ); - if ( msg.hasKey( "optional" ) ) + if( msg.hasKey( "optional" ) ) { NBTTagCompound optionalTag = (NBTTagCompound) msg.getTag( "optional" ); ItemStack optional = ItemStack.loadItemStackFromNBT( optionalTag ); - if ( optional == null ) + if( optional == null ) throw new RuntimeException( "invalid optional" ); float chance = msg.getFloat( "chance" ); diff --git a/src/main/java/appeng/core/api/imc/IMCMatterCannon.java b/src/main/java/appeng/core/api/imc/IMCMatterCannon.java index 612ef34b4..81e574c86 100644 --- a/src/main/java/appeng/core/api/imc/IMCMatterCannon.java +++ b/src/main/java/appeng/core/api/imc/IMCMatterCannon.java @@ -28,8 +28,10 @@ msg.setDouble( "weight", 32.0 ); FMLInterModComms.sendMessage( "appliedenergistics2", "add-mattercannon-ammo", msg ); */ + package appeng.core.api.imc; + import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -38,6 +40,7 @@ import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import appeng.api.AEApi; import appeng.core.api.IIMCProcessor; + public class IMCMatterCannon implements IIMCProcessor { @@ -50,7 +53,7 @@ public class IMCMatterCannon implements IIMCProcessor ItemStack ammo = ItemStack.loadItemStackFromNBT( item ); double weight = msg.getDouble( "weight" ); - if ( ammo == null ) + if( ammo == null ) throw new RuntimeException( "invalid item" ); AEApi.instance().registries().matterCannon().registerAmmo( ammo, weight ); diff --git a/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java b/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java index 7614bef99..40dd1cd32 100644 --- a/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java +++ b/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java @@ -26,8 +26,10 @@ FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-fluid", FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-item", new ItemStack( myBlockOrItem ) ); */ + package appeng.core.api.imc; + import net.minecraft.item.ItemStack; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; @@ -36,6 +38,7 @@ import appeng.api.AEApi; import appeng.api.config.TunnelType; import appeng.core.api.IIMCProcessor; + public class IMCP2PAttunement implements IIMCProcessor { @@ -46,10 +49,10 @@ public class IMCP2PAttunement implements IIMCProcessor TunnelType type = TunnelType.valueOf( key ); - if ( type != null ) + if( type != null ) { ItemStack is = m.getItemStackValue(); - if ( is != null ) + if( is != null ) AEApi.instance().registries().p2pTunnel().addNewAttunement( is, type ); else throw new RuntimeException( "invalid item" ); @@ -57,5 +60,4 @@ public class IMCP2PAttunement implements IIMCProcessor else throw new RuntimeException( "invalid type" ); } - } diff --git a/src/main/java/appeng/core/api/imc/IMCSpatial.java b/src/main/java/appeng/core/api/imc/IMCSpatial.java index a1b93f5a2..fb82b7737 100644 --- a/src/main/java/appeng/core/api/imc/IMCSpatial.java +++ b/src/main/java/appeng/core/api/imc/IMCSpatial.java @@ -21,14 +21,17 @@ FMLInterModComms.sendMessage( "appliedenergistics2", "whitelist-spatial", "mymod.tileentities.MyTileEntity" ); */ + package appeng.core.api.imc; + import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import appeng.api.AEApi; import appeng.core.AELog; import appeng.core.api.IIMCProcessor; + public class IMCSpatial implements IIMCProcessor { @@ -41,11 +44,9 @@ public class IMCSpatial implements IIMCProcessor Class classInstance = Class.forName( m.getStringValue() ); AEApi.instance().registries().movable().whiteListTileEntity( classInstance ); } - catch (ClassNotFoundException e) + catch( ClassNotFoundException e ) { AELog.info( "Bad Class Registered: " + m.getStringValue() + " by " + m.getSender() ); } - } - } diff --git a/src/main/java/appeng/core/crash/CrashInfo.java b/src/main/java/appeng/core/crash/CrashInfo.java index a7a8cbbf6..7a25618f1 100644 --- a/src/main/java/appeng/core/crash/CrashInfo.java +++ b/src/main/java/appeng/core/crash/CrashInfo.java @@ -18,6 +18,7 @@ package appeng.core.crash; + public enum CrashInfo { MOD_VERSION, INTEGRATION diff --git a/src/main/java/appeng/core/features/AEBlockFeatureHandler.java b/src/main/java/appeng/core/features/AEBlockFeatureHandler.java index c4d134e0e..ea5adfa70 100644 --- a/src/main/java/appeng/core/features/AEBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/AEBlockFeatureHandler.java @@ -64,14 +64,14 @@ public final class AEBlockFeatureHandler implements IFeatureHandler @Override public void register() { - if ( this.enabled ) + if( this.enabled ) { String name = this.extractor.get(); this.featured.setCreativeTab( CreativeTab.instance ); this.featured.setBlockName( /* "tile." */"appliedenergistics2." + name ); this.featured.setBlockTextureName( "appliedenergistics2:" + name ); - if ( Platform.isClient() ) + if( Platform.isClient() ) { CommonHelper.proxy.bindTileEntitySpecialRenderer( this.featured.getTileEntityClass(), this.featured ); } diff --git a/src/main/java/appeng/core/features/AEFeature.java b/src/main/java/appeng/core/features/AEFeature.java index 3f9ac3aa8..49beded73 100644 --- a/src/main/java/appeng/core/features/AEFeature.java +++ b/src/main/java/appeng/core/features/AEFeature.java @@ -18,73 +18,74 @@ package appeng.core.features; + public enum AEFeature { - Core(null), // stuff that has no reason for ever being turned off, or that - // is just flat out required by tons of - // important stuff. + Core( null ), // stuff that has no reason for ever being turned off, or that + // is just flat out required by tons of + // important stuff. - CertusQuartzWorldGen("World"), MeteoriteWorldGen("World"), + CertusQuartzWorldGen( "World" ), MeteoriteWorldGen( "World" ), - DecorativeLights("World"), DecorativeQuartzBlocks("World"), SkyStoneChests("World"), SpawnPressesInMeteorites("World"), + DecorativeLights( "World" ), DecorativeQuartzBlocks( "World" ), SkyStoneChests( "World" ), SpawnPressesInMeteorites( "World" ), - GrindStone("World"), Flour("World"), Inscriber("World"), + GrindStone( "World" ), Flour( "World" ), Inscriber( "World" ), - ChestLoot("World"), VillagerTrading("World"), + ChestLoot( "World" ), VillagerTrading( "World" ), - TinyTNT("World"), + TinyTNT( "World" ), - PoweredTools("ToolsClassifications"), + PoweredTools( "ToolsClassifications" ), - CertusQuartzTools("ToolsClassifications"), + CertusQuartzTools( "ToolsClassifications" ), - NetherQuartzTools("ToolsClassifications"), + NetherQuartzTools( "ToolsClassifications" ), - QuartzHoe("Tools"), QuartzSpade("Tools"), QuartzSword("Tools"), QuartzPickaxe("Tools"), QuartzAxe("Tools"), QuartzKnife("Tools"), QuartzWrench("Tools"), + QuartzHoe( "Tools" ), QuartzSpade( "Tools" ), QuartzSword( "Tools" ), QuartzPickaxe( "Tools" ), QuartzAxe( "Tools" ), QuartzKnife( "Tools" ), QuartzWrench( "Tools" ), - ChargedStaff("Tools"), EntropyManipulator("Tools"), MatterCannon("Tools"), WirelessAccessTerminal("Tools"), ColorApplicator("Tools"), + ChargedStaff( "Tools" ), EntropyManipulator( "Tools" ), MatterCannon( "Tools" ), WirelessAccessTerminal( "Tools" ), ColorApplicator( "Tools" ), - CraftingCPU("CraftingFeatures"), PowerGen("NetworkFeatures"), Security("NetworkFeatures"), + CraftingCPU( "CraftingFeatures" ), PowerGen( "NetworkFeatures" ), Security( "NetworkFeatures" ), - SpatialIO("NetworkFeatures"), QuantumNetworkBridge("NetworkFeatures"), Channels("NetworkFeatures"), + SpatialIO( "NetworkFeatures" ), QuantumNetworkBridge( "NetworkFeatures" ), Channels( "NetworkFeatures" ), - LevelEmitter("NetworkBuses"), CraftingTerminal("NetworkBuses"), StorageMonitor("NetworkBuses"), P2PTunnel("NetworkBuses"), FormationPlane("NetworkBuses"), AnnihilationPlane( - "NetworkBuses"), ImportBus("NetworkBuses"), ExportBus("NetworkBuses"), StorageBus("NetworkBuses"), PartConversionMonitor("NetworkBuses"), + LevelEmitter( "NetworkBuses" ), CraftingTerminal( "NetworkBuses" ), StorageMonitor( "NetworkBuses" ), P2PTunnel( "NetworkBuses" ), FormationPlane( "NetworkBuses" ), AnnihilationPlane( "NetworkBuses" ), ImportBus( "NetworkBuses" ), ExportBus( "NetworkBuses" ), StorageBus( "NetworkBuses" ), PartConversionMonitor( "NetworkBuses" ), - StorageCells("Storage"), PortableCell("PortableCell"), MEChest("Storage"), MEDrive("Storage"), IOPort("Storage"), + StorageCells( "Storage" ), PortableCell( "PortableCell" ), MEChest( "Storage" ), MEDrive( "Storage" ), IOPort( "Storage" ), - NetworkTool("NetworkTool"), + NetworkTool( "NetworkTool" ), - DenseEnergyCells("HigherCapacity"), DenseCables("HigherCapacity"), + DenseEnergyCells( "HigherCapacity" ), DenseCables( "HigherCapacity" ), - P2PTunnelRF("P2PTunnels"), P2PTunnelME("P2PTunnels"), P2PTunnelItems("P2PTunnels"), P2PTunnelRedstone("P2PTunnels"), P2PTunnelEU("P2PTunnels"), P2PTunnelMJ( - "P2PTunnels"), P2PTunnelLiquids("P2PTunnels"), P2PTunnelLight("P2PTunnels"), + P2PTunnelRF( "P2PTunnels" ), P2PTunnelME( "P2PTunnels" ), P2PTunnelItems( "P2PTunnels" ), P2PTunnelRedstone( "P2PTunnels" ), P2PTunnelEU( "P2PTunnels" ), P2PTunnelMJ( "P2PTunnels" ), P2PTunnelLiquids( "P2PTunnels" ), P2PTunnelLight( "P2PTunnels" ), - MassCannonBlockDamage("BlockFeatures"), TinyTNTBlockDamage("BlockFeatures"), Facades("Facades"), + MassCannonBlockDamage( "BlockFeatures" ), TinyTNTBlockDamage( "BlockFeatures" ), Facades( "Facades" ), - UnsupportedDeveloperTools("Misc", false), Creative("Misc"), + UnsupportedDeveloperTools( "Misc", false ), Creative( "Misc" ), - GrinderLogging("Misc", false), Logging("Misc"), IntegrationLogging("Misc", false), CustomRecipes("Crafting", false), WebsiteRecipes("Misc", false), + GrinderLogging( "Misc", false ), Logging( "Misc" ), IntegrationLogging( "Misc", false ), CustomRecipes( "Crafting", false ), WebsiteRecipes( "Misc", false ), - enableFacadeCrafting("Crafting"), inWorldSingularity("Crafting"), inWorldFluix("Crafting"), inWorldPurification("Crafting"), UpdateLogging("Misc", false), + enableFacadeCrafting( "Crafting" ), inWorldSingularity( "Crafting" ), inWorldFluix( "Crafting" ), inWorldPurification( "Crafting" ), UpdateLogging( "Misc", false ), - AlphaPass("Rendering"), PaintBalls("Tools"), PacketLogging("Misc", false), CraftingLog("Misc", false), InterfaceTerminal("Crafting"), LightDetector("Misc"), + AlphaPass( "Rendering" ), PaintBalls( "Tools" ), PacketLogging( "Misc", false ), CraftingLog( "Misc", false ), InterfaceTerminal( "Crafting" ), LightDetector( "Misc" ), - enableDisassemblyCrafting("Crafting"), MolecularAssembler("CraftingFeatures"), MeteoriteCompass("Tools"), Patterns("CraftingFeatures"), + enableDisassemblyCrafting( "Crafting" ), MolecularAssembler( "CraftingFeatures" ), MeteoriteCompass( "Tools" ), Patterns( "CraftingFeatures" ), - ChunkLoggerTrace("Commands", false), LogSecurityAudits("Misc", false), Achievements("Misc"); + ChunkLoggerTrace( "Commands", false ), LogSecurityAudits( "Misc", false ), Achievements( "Misc" ); public final String category; public final boolean isVisible; public final boolean defaultValue; - AEFeature( String cat ) { + AEFeature( String cat ) + { this.category = cat; this.isVisible = !this.name().equals( "Core" ); this.defaultValue = true; } - AEFeature( String cat, boolean defaultValue ) { + AEFeature( String cat, boolean defaultValue ) + { this.category = cat; this.isVisible = !this.name().equals( "Core" ); this.defaultValue = defaultValue; diff --git a/src/main/java/appeng/core/features/BlockDefinition.java b/src/main/java/appeng/core/features/BlockDefinition.java index 3908cbe95..e50c403f0 100644 --- a/src/main/java/appeng/core/features/BlockDefinition.java +++ b/src/main/java/appeng/core/features/BlockDefinition.java @@ -57,7 +57,7 @@ public class BlockDefinition extends ItemDefinition implements IBlockDefinition @Override public Optional maybeItemBlock() { - if ( this.enabled ) + if( this.enabled ) { return Optional.of( new ItemBlock( this.block ) ); } @@ -70,7 +70,7 @@ public class BlockDefinition extends ItemDefinition implements IBlockDefinition @Override public final Optional maybeStack( int stackSize ) { - if ( this.enabled ) + if( this.enabled ) { return Optional.of( new ItemStack( this.block ) ); } diff --git a/src/main/java/appeng/core/features/ColoredItemDefinition.java b/src/main/java/appeng/core/features/ColoredItemDefinition.java index 16fe7e4b2..d777a5074 100644 --- a/src/main/java/appeng/core/features/ColoredItemDefinition.java +++ b/src/main/java/appeng/core/features/ColoredItemDefinition.java @@ -18,6 +18,7 @@ package appeng.core.features; + import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -26,68 +27,68 @@ import net.minecraft.tileentity.TileEntity; import appeng.api.util.AEColor; import appeng.api.util.AEColoredItemDefinition; + public final class ColoredItemDefinition implements AEColoredItemDefinition { final ItemStackSrc[] colors = new ItemStackSrc[17]; + public void add( AEColor v, ItemStackSrc is ) + { + this.colors[v.ordinal()] = is; + } + @Override - public Item item(AEColor color) + public Block block( AEColor color ) + { + return null; + } + + @Override + public Item item( AEColor color ) { ItemStackSrc is = this.colors[color.ordinal()]; - if ( is == null ) + if( is == null ) return null; return is.item; } @Override - public ItemStack stack(AEColor color, int stackSize) + public Class entity( AEColor color ) + { + return null; + } + + @Override + public ItemStack stack( AEColor color, int stackSize ) { ItemStackSrc is = this.colors[color.ordinal()]; - if ( is == null ) + if( is == null ) return null; return is.stack( stackSize ); } @Override - public boolean sameAs(AEColor color, ItemStack comparableItem) - { - ItemStackSrc is = this.colors[color.ordinal()]; - - if ( comparableItem == null || is == null ) - return false; - - return comparableItem.getItem() == is.item && comparableItem.getItemDamage() == is.damage; - } - - public void add(AEColor v, ItemStackSrc is) - { - this.colors[v.ordinal()] = is; - } - - @Override - public Block block(AEColor color) - { - return null; - } - - @Override - public Class entity(AEColor color) - { - return null; - } - - @Override - public ItemStack[] allStacks(int stackSize) + public ItemStack[] allStacks( int stackSize ) { ItemStack[] is = new ItemStack[this.colors.length]; - for (int x = 0; x < is.length; x++) + for( int x = 0; x < is.length; x++ ) is[x] = this.colors[x].stack( 1 ); return is; } + @Override + public boolean sameAs( AEColor color, ItemStack comparableItem ) + { + ItemStackSrc is = this.colors[color.ordinal()]; + + if( comparableItem == null || is == null ) + return false; + + return comparableItem.getItem() == is.item && comparableItem.getItemDamage() == is.damage; + } } diff --git a/src/main/java/appeng/core/features/DamagedItemDefinition.java b/src/main/java/appeng/core/features/DamagedItemDefinition.java index d6a6c0e84..05913032c 100644 --- a/src/main/java/appeng/core/features/DamagedItemDefinition.java +++ b/src/main/java/appeng/core/features/DamagedItemDefinition.java @@ -56,7 +56,7 @@ public final class DamagedItemDefinition implements IItemDefinition @Override public boolean isSameAs( ItemStack comparableStack ) { - if ( comparableStack == null ) + if( comparableStack == null ) return false; return comparableStack.getItem() == this.source.getItem() && comparableStack.getItemDamage() == this.source.getDamage(); diff --git a/src/main/java/appeng/core/features/DefinitionConverter.java b/src/main/java/appeng/core/features/DefinitionConverter.java index 9b8821f23..bcad08c05 100644 --- a/src/main/java/appeng/core/features/DefinitionConverter.java +++ b/src/main/java/appeng/core/features/DefinitionConverter.java @@ -92,6 +92,7 @@ public final class DefinitionConverter } } + private static class AEItem extends AEComparable { private final IItemDefinition definition; @@ -118,6 +119,7 @@ public final class DefinitionConverter } } + private static class AEBlock extends AEItem { private final IBlockDefinition definition; @@ -137,6 +139,7 @@ public final class DefinitionConverter } } + private static class AETile extends AEBlock { private final ITileDefinition definition; @@ -155,6 +158,4 @@ public final class DefinitionConverter return this.definition.maybeEntity().orNull(); } } - - } diff --git a/src/main/java/appeng/core/features/FeatureNameExtractor.java b/src/main/java/appeng/core/features/FeatureNameExtractor.java index f1fb0bf64..75f47c74c 100644 --- a/src/main/java/appeng/core/features/FeatureNameExtractor.java +++ b/src/main/java/appeng/core/features/FeatureNameExtractor.java @@ -43,29 +43,29 @@ public class FeatureNameExtractor { String name = this.clazz.getSimpleName(); - if ( name.startsWith( "ItemMultiPart" ) ) + if( name.startsWith( "ItemMultiPart" ) ) { name = PATTERN_ITEM_MULTI_PART.matcher( name ).replaceAll( "ItemPart" ); } - else if ( name.startsWith( "ItemMultiMaterial" ) ) + else if( name.startsWith( "ItemMultiMaterial" ) ) { name = PATTERN_ITEM_MULTI_MATERIAL.matcher( name ).replaceAll( "ItemMaterial" ); } - if ( this.subName.isPresent() ) + if( this.subName.isPresent() ) { final String subName = this.subName.get(); // simple hack to allow me to do get nice names for these without // mode code outside of AEBaseItem - if ( subName.startsWith( "P2PTunnel" ) ) + if( subName.startsWith( "P2PTunnel" ) ) { return "ItemPart.P2PTunnel"; } - else if ( subName.equals( "CertusQuartzTools" ) ) + else if( subName.equals( "CertusQuartzTools" ) ) { return PATTERN_QUARTZ.matcher( name ).replaceAll( "CertusQuartz" ); } - else if ( subName.equals( "NetherQuartzTools" ) ) + else if( subName.equals( "NetherQuartzTools" ) ) { return PATTERN_QUARTZ.matcher( name ).replaceAll( "NetherQuartz" ); } diff --git a/src/main/java/appeng/core/features/FeaturedActiveChecker.java b/src/main/java/appeng/core/features/FeaturedActiveChecker.java index 001961505..cf74d1371 100644 --- a/src/main/java/appeng/core/features/FeaturedActiveChecker.java +++ b/src/main/java/appeng/core/features/FeaturedActiveChecker.java @@ -35,9 +35,9 @@ public class FeaturedActiveChecker public ActivityState getActivityState() { - for ( AEFeature f : this.features ) + for( AEFeature f : this.features ) { - if ( !AEConfig.instance.isFeatureEnabled( f ) ) + if( !AEConfig.instance.isFeatureEnabled( f ) ) { return ActivityState.Disabled; } diff --git a/src/main/java/appeng/core/features/IStackSrc.java b/src/main/java/appeng/core/features/IStackSrc.java index 1bb485e7e..4f10410a8 100644 --- a/src/main/java/appeng/core/features/IStackSrc.java +++ b/src/main/java/appeng/core/features/IStackSrc.java @@ -18,16 +18,17 @@ package appeng.core.features; + import net.minecraft.item.Item; import net.minecraft.item.ItemStack; + public interface IStackSrc { - ItemStack stack(int i); + ItemStack stack( int i ); Item getItem(); int getDamage(); - } diff --git a/src/main/java/appeng/core/features/ItemDefinition.java b/src/main/java/appeng/core/features/ItemDefinition.java index 28aa143cc..f607b87a9 100644 --- a/src/main/java/appeng/core/features/ItemDefinition.java +++ b/src/main/java/appeng/core/features/ItemDefinition.java @@ -51,7 +51,7 @@ public class ItemDefinition implements IItemDefinition @Override public Optional maybeStack( int stackSize ) { - if ( this.enabled ) + if( this.enabled ) { return Optional.of( new ItemStack( this.item ) ); } diff --git a/src/main/java/appeng/core/features/ItemFeatureHandler.java b/src/main/java/appeng/core/features/ItemFeatureHandler.java index 1739bc4dc..2c1daed61 100644 --- a/src/main/java/appeng/core/features/ItemFeatureHandler.java +++ b/src/main/java/appeng/core/features/ItemFeatureHandler.java @@ -65,13 +65,13 @@ public final class ItemFeatureHandler implements IFeatureHandler @Override public void register() { - if ( this.enabled ) + if( this.enabled ) { String name = this.extractor.get(); this.item.setTextureName( "appliedenergistics2:" + name ); this.item.setUnlocalizedName( /* "item." */"appliedenergistics2." + name ); - if ( this.item instanceof ItemFacade ) + if( this.item instanceof ItemFacade ) { this.item.setCreativeTab( CreativeTabFacade.instance ); } @@ -80,11 +80,11 @@ public final class ItemFeatureHandler implements IFeatureHandler this.item.setCreativeTab( CreativeTab.instance ); } - if ( name.equals( "ItemMaterial" ) ) + if( name.equals( "ItemMaterial" ) ) { name = "ItemMultiMaterial"; } - else if ( name.equals( "ItemPart" ) ) + else if( name.equals( "ItemPart" ) ) { name = "ItemMultiPart"; } diff --git a/src/main/java/appeng/core/features/ItemStackSrc.java b/src/main/java/appeng/core/features/ItemStackSrc.java index 119288b0b..7d6cd2bc2 100644 --- a/src/main/java/appeng/core/features/ItemStackSrc.java +++ b/src/main/java/appeng/core/features/ItemStackSrc.java @@ -18,10 +18,12 @@ package appeng.core.features; + import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; + public class ItemStackSrc implements IStackSrc { @@ -29,25 +31,27 @@ public class ItemStackSrc implements IStackSrc public final Block block; public final int damage; - public ItemStackSrc(Item i, int dmg) { + public ItemStackSrc( Item i, int dmg ) + { this.block = null; this.item = i; this.damage = dmg; } - public ItemStackSrc(Block b, int dmg) { + public ItemStackSrc( Block b, int dmg ) + { this.item = null; this.block = b; this.damage = dmg; } @Override - public ItemStack stack(int i) + public ItemStack stack( int i ) { - if ( this.block != null ) + if( this.block != null ) return new ItemStack( this.block, i, this.damage ); - if ( this.item != null ) + if( this.item != null ) return new ItemStack( this.item, i, this.damage ); return null; diff --git a/src/main/java/appeng/core/features/NameResolver.java b/src/main/java/appeng/core/features/NameResolver.java index 84e6ad865..f3caec2dd 100644 --- a/src/main/java/appeng/core/features/NameResolver.java +++ b/src/main/java/appeng/core/features/NameResolver.java @@ -41,7 +41,7 @@ public final class NameResolver private final Class withOriginalName; - public NameResolver( Class withOriginalName) + public NameResolver( Class withOriginalName ) { this.withOriginalName = withOriginalName; } @@ -50,21 +50,21 @@ public final class NameResolver { String name = this.withOriginalName.getSimpleName(); - if ( name.startsWith( "ItemMultiPart" ) ) + if( name.startsWith( "ItemMultiPart" ) ) name = ITEM_MULTI_PART.matcher( name ).replaceAll( "ItemPart" ); - else if ( name.startsWith( "ItemMultiMaterial" ) ) + else if( name.startsWith( "ItemMultiMaterial" ) ) name = ITEM_MULTI_MATERIAL.matcher( name ).replaceAll( "ItemMaterial" ); - if ( subName != null ) + if( subName != null ) { // simple hack to allow me to do get nice names for these without // mode code outside of AEBaseItem - if ( subName.startsWith( "P2PTunnel" ) ) + if( subName.startsWith( "P2PTunnel" ) ) return "ItemPart.P2PTunnel"; - if ( subName.equals( "CertusQuartzTools" ) ) + if( subName.equals( "CertusQuartzTools" ) ) return QUARTZ.matcher( name ).replaceAll( "CertusQuartz" ); - if ( subName.equals( "NetherQuartzTools" ) ) + if( subName.equals( "NetherQuartzTools" ) ) return QUARTZ.matcher( name ).replaceAll( "NetherQuartz" ); name += '.' + subName; diff --git a/src/main/java/appeng/core/features/StairBlockFeatureHandler.java b/src/main/java/appeng/core/features/StairBlockFeatureHandler.java index cedc4b111..7abb6122c 100644 --- a/src/main/java/appeng/core/features/StairBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/StairBlockFeatureHandler.java @@ -63,7 +63,7 @@ public class StairBlockFeatureHandler implements IFeatureHandler @Override public final void register() { - if ( this.enabled ) + if( this.enabled ) { String name = this.extractor.get(); this.stairs.setCreativeTab( CreativeTab.instance ); diff --git a/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java b/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java index 73410b789..6020641b3 100644 --- a/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java +++ b/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java @@ -78,7 +78,7 @@ public final class WrappedDamageItemDefinition implements ITileDefinition @Override public boolean isSameAs( ItemStack comparableStack ) { - if ( comparableStack == null ) + if( comparableStack == null ) return false; return this.definition.isSameAs( comparableStack ) && comparableStack.getItemDamage() == this.damage; diff --git a/src/main/java/appeng/core/features/registries/CellRegistry.java b/src/main/java/appeng/core/features/registries/CellRegistry.java index def0e314f..d658cc734 100644 --- a/src/main/java/appeng/core/features/registries/CellRegistry.java +++ b/src/main/java/appeng/core/features/registries/CellRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.util.ArrayList; import java.util.List; @@ -29,41 +30,43 @@ import appeng.api.storage.IMEInventoryHandler; import appeng.api.storage.ISaveProvider; import appeng.api.storage.StorageChannel; + public class CellRegistry implements ICellRegistry { final List handlers; - public CellRegistry() { + public CellRegistry() + { this.handlers = new ArrayList(); } @Override - public void addCellHandler(ICellHandler h) + public void addCellHandler( ICellHandler h ) { - if ( h != null ) + if( h != null ) this.handlers.add( h ); } @Override - public boolean isCellHandled(ItemStack is) + public boolean isCellHandled( ItemStack is ) { - if ( is == null ) + if( is == null ) return false; - for (ICellHandler ch : this.handlers) - if ( ch.isCell( is ) ) + for( ICellHandler ch : this.handlers ) + if( ch.isCell( is ) ) return true; return false; } @Override - public ICellHandler getHandler(ItemStack is) + public ICellHandler getHandler( ItemStack is ) { - if ( is == null ) + if( is == null ) return null; - for (ICellHandler ch : this.handlers) + for( ICellHandler ch : this.handlers ) { - if ( ch.isCell( is ) ) + if( ch.isCell( is ) ) { return ch; } @@ -72,13 +75,13 @@ public class CellRegistry implements ICellRegistry } @Override - public IMEInventoryHandler getCellInventory(ItemStack is, ISaveProvider container, StorageChannel chan) + public IMEInventoryHandler getCellInventory( ItemStack is, ISaveProvider container, StorageChannel chan ) { - if ( is == null ) + if( is == null ) return null; - for (ICellHandler ch : this.handlers) + for( ICellHandler ch : this.handlers ) { - if ( ch.isCell( is ) ) + if( ch.isCell( is ) ) { return ch.getCellInventory( is, container, chan ); } diff --git a/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java b/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java index afdc0bc16..46cc1eec1 100644 --- a/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java +++ b/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.util.ArrayList; import java.util.List; @@ -30,35 +31,36 @@ import appeng.api.storage.IExternalStorageRegistry; import appeng.api.storage.StorageChannel; import appeng.core.features.registries.entries.ExternalIInv; + public class ExternalStorageRegistry implements IExternalStorageRegistry { final List Handlers; final ExternalIInv lastHandler = new ExternalIInv(); - public ExternalStorageRegistry() { + public ExternalStorageRegistry() + { this.Handlers = new ArrayList(); } @Override - public IExternalStorageHandler getHandler(TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource mySrc) - { - for (IExternalStorageHandler x : this.Handlers) - { - if ( x.canHandle( te, d, chan, mySrc ) ) - return x; - } - - if ( this.lastHandler.canHandle( te, d, chan, mySrc ) ) - return this.lastHandler; - - return null; - } - - @Override - public void addExternalStorageInterface(IExternalStorageHandler ei) + public void addExternalStorageInterface( IExternalStorageHandler ei ) { this.Handlers.add( ei ); } + @Override + public IExternalStorageHandler getHandler( TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource mySrc ) + { + for( IExternalStorageHandler x : this.Handlers ) + { + if( x.canHandle( te, d, chan, mySrc ) ) + return x; + } + + if( this.lastHandler.canHandle( te, d, chan, mySrc ) ) + return this.lastHandler; + + return null; + } } diff --git a/src/main/java/appeng/core/features/registries/GridCacheRegistry.java b/src/main/java/appeng/core/features/registries/GridCacheRegistry.java index f538d5750..dbe23d80b 100644 --- a/src/main/java/appeng/core/features/registries/GridCacheRegistry.java +++ b/src/main/java/appeng/core/features/registries/GridCacheRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.lang.reflect.Constructor; import java.util.HashMap; @@ -26,33 +27,34 @@ import appeng.api.networking.IGridCache; import appeng.api.networking.IGridCacheRegistry; import appeng.core.AELog; + public class GridCacheRegistry implements IGridCacheRegistry { final private HashMap, Class> caches = new HashMap, Class>(); @Override - public void registerGridCache(Class iface, Class implementation) + public void registerGridCache( Class iface, Class implementation ) { - if ( iface.isAssignableFrom( implementation ) ) + if( iface.isAssignableFrom( implementation ) ) this.caches.put( iface, implementation ); else throw new RuntimeException( "Invalid setup, grid cache must either be the same class, or an interface that the implementation implements" ); } @Override - public HashMap, IGridCache> createCacheInstance(IGrid g) + public HashMap, IGridCache> createCacheInstance( IGrid g ) { HashMap, IGridCache> map = new HashMap, IGridCache>(); - for (Class iface : this.caches.keySet()) + for( Class iface : this.caches.keySet() ) { try { Constructor c = this.caches.get( iface ).getConstructor( IGrid.class ); map.put( iface, c.newInstance( g ) ); } - catch (Throwable e) + catch( Throwable e ) { AELog.severe( "Grid Caches must have a constructor with IGrid as the single param." ); throw new RuntimeException( e ); diff --git a/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java b/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java index 65a035d88..434b82f6b 100644 --- a/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java +++ b/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java @@ -85,7 +85,7 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene @Override public void addRecipe( ItemStack in, ItemStack out, int cost ) { - if ( in == null || out == null ) + if( in == null || out == null ) { this.log( "Invalid Grinder Recipe Specified." ); return; @@ -98,7 +98,7 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene @Override public void addRecipe( ItemStack in, ItemStack out, ItemStack optional, float chance, int cost ) { - if ( in == null || ( optional == null && out == null ) ) + if( in == null || ( optional == null && out == null ) ) { this.log( "Invalid Grinder Recipe Specified." ); return; @@ -111,7 +111,7 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene @Override public void addRecipe( ItemStack in, ItemStack out, ItemStack optional, float chance, ItemStack optional2, float chance2, int cost ) { - if ( in == null || ( optional == null && out == null && optional2 == null ) ) + if( in == null || ( optional == null && out == null && optional2 == null ) ) { this.log( "Invalid Grinder Recipe Specified." ); return; @@ -123,8 +123,8 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene private void injectRecipe( AppEngGrinderRecipe appEngGrinderRecipe ) { - for ( IGrinderEntry gr : this.recipes ) - if ( Platform.isSameItemPrecise( gr.getInput(), appEngGrinderRecipe.getInput() ) ) + for( IGrinderEntry gr : this.recipes ) + if( Platform.isSameItemPrecise( gr.getInput(), appEngGrinderRecipe.getInput() ) ) return; this.recipes.add( appEngGrinderRecipe ); @@ -132,7 +132,7 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene private ItemStack copy( ItemStack is ) { - if ( is != null ) + if( is != null ) return is.copy(); return null; } @@ -141,11 +141,11 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene public IGrinderEntry getRecipeForInput( ItemStack input ) { this.log( "Looking up recipe for " + Platform.getItemDisplayName( input ) ); - if ( input != null ) + if( input != null ) { - for ( IGrinderEntry r : this.recipes ) + for( IGrinderEntry r : this.recipes ) { - if ( Platform.isSameItem( input, r.getInput() ) ) + if( Platform.isSameItem( input, r.getInput() ) ) { this.log( "Recipe for " + input.getUnlocalizedName() + " found " + Platform.getItemDisplayName( r.getOutput() ) ); return r; @@ -165,28 +165,28 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene private int getDustToOreRatio( String name ) { - if ( name.equals( "Obsidian" ) ) + if( name.equals( "Obsidian" ) ) return 1; - if ( name.equals( "Charcoal" ) ) + if( name.equals( "Charcoal" ) ) return 1; - if ( name.equals( "Coal" ) ) + if( name.equals( "Coal" ) ) return 1; return 2; } private void addOre( String name, ItemStack item ) { - if ( item == null ) + if( item == null ) return; this.log( "Adding Ore - " + name + " : " + Platform.getItemDisplayName( item ) ); this.ores.put( item, name ); - if ( this.dusts.containsKey( name ) ) + if( this.dusts.containsKey( name ) ) { ItemStack is = this.dusts.get( name ).copy(); int ratio = this.getDustToOreRatio( name ); - if ( ratio > 1 ) + if( ratio > 1 ) { ItemStack extra = is.copy(); extra.stackSize = ratio - 1; @@ -199,13 +199,13 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene private void addIngot( String name, ItemStack item ) { - if ( item == null ) + if( item == null ) return; this.log( "Adding Ingot - " + name + " : " + Platform.getItemDisplayName( item ) ); this.ingots.put( item, name ); - if ( this.dusts.containsKey( name ) ) + if( this.dusts.containsKey( name ) ) { this.addRecipe( item, this.dusts.get( name ), 4 ); } @@ -213,9 +213,9 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene private void addDust( String name, ItemStack item ) { - if ( item == null ) + if( item == null ) return; - if ( this.dusts.containsKey( name ) ) + if( this.dusts.containsKey( name ) ) { this.log( "Rejecting Dust - " + name + " : " + Platform.getItemDisplayName( item ) ); return; @@ -225,13 +225,13 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene this.dusts.put( name, item ); - for ( Entry d : this.ores.entrySet() ) - if ( name.equals( d.getValue() ) ) + for( Entry d : this.ores.entrySet() ) + if( name.equals( d.getValue() ) ) { ItemStack is = item.copy(); is.stackSize = 1; int ratio = this.getDustToOreRatio( name ); - if ( ratio > 1 ) + if( ratio > 1 ) { ItemStack extra = is.copy(); extra.stackSize = ratio - 1; @@ -241,27 +241,27 @@ public final class GrinderRecipeManager implements IGrinderRegistry, IOreListene this.addRecipe( d.getKey(), is, 8 ); } - for ( Entry d : this.ingots.entrySet() ) - if ( name.equals( d.getValue() ) ) + for( Entry d : this.ingots.entrySet() ) + if( name.equals( d.getValue() ) ) this.addRecipe( d.getKey(), item, 4 ); } @Override public void oreRegistered( String name, ItemStack item ) { - if ( name.startsWith( "ore" ) || name.startsWith( "crystal" ) || name.startsWith( "gem" ) || name.startsWith( "ingot" ) || name.startsWith( "dust" ) ) + if( name.startsWith( "ore" ) || name.startsWith( "crystal" ) || name.startsWith( "gem" ) || name.startsWith( "ingot" ) || name.startsWith( "dust" ) ) { - for ( String ore : AEConfig.instance.grinderOres ) + for( String ore : AEConfig.instance.grinderOres ) { - if ( name.equals( "ore" + ore ) ) + if( name.equals( "ore" + ore ) ) { this.addOre( ore, item ); } - else if ( name.equals( "crystal" + ore ) || name.equals( "ingot" + ore ) || name.equals( "gem" + ore ) ) + else if( name.equals( "crystal" + ore ) || name.equals( "ingot" + ore ) || name.equals( "gem" + ore ) ) { this.addIngot( ore, item ); } - else if ( name.equals( "dust" + ore ) ) + else if( name.equals( "dust" + ore ) ) { this.addDust( ore, item ); } diff --git a/src/main/java/appeng/core/features/registries/LocatableRegistry.java b/src/main/java/appeng/core/features/registries/LocatableRegistry.java index d50b88036..6bd890cef 100644 --- a/src/main/java/appeng/core/features/registries/LocatableRegistry.java +++ b/src/main/java/appeng/core/features/registries/LocatableRegistry.java @@ -46,14 +46,14 @@ public final class LocatableRegistry implements ILocatableRegistry @SubscribeEvent public void updateLocatable( LocatableEventAnnounce e ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; // IGNORE! - if ( e.change == LocatableEvent.Register ) + if( e.change == LocatableEvent.Register ) { this.set.put( e.target.getLocatableSerial(), e.target ); } - else if ( e.change == LocatableEvent.Unregister ) + else if( e.change == LocatableEvent.Unregister ) { this.set.remove( e.target.getLocatableSerial() ); } diff --git a/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java b/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java index a75246710..b406f3957 100644 --- a/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java +++ b/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.util.HashMap; import net.minecraft.init.Items; @@ -28,29 +29,39 @@ import appeng.recipes.ores.IOreListener; import appeng.recipes.ores.OreDictionaryHandler; import appeng.util.Platform; + public class MatterCannonAmmoRegistry implements IOreListener, IMatterCannonAmmoRegistry { private final HashMap DamageModifiers = new HashMap(); + public MatterCannonAmmoRegistry() + { + OreDictionaryHandler.INSTANCE.observe( this ); + this.registerAmmo( new ItemStack( Items.gold_nugget ), 196.96655 ); + } + @Override - public void registerAmmo(ItemStack ammo, double weight) + public void registerAmmo( ItemStack ammo, double weight ) { this.DamageModifiers.put( ammo, weight ); } - private void considerItem(String ore, ItemStack item, String Name, double weight) + @Override + public float getPenetration( ItemStack is ) { - if ( ore.equals( "berry" + Name ) || ore.equals( "nugget" + Name ) ) + for( ItemStack o : this.DamageModifiers.keySet() ) { - this.registerAmmo( item, weight ); + if( Platform.isSameItem( o, is ) ) + return this.DamageModifiers.get( o ).floatValue(); } + return 0; } @Override - public void oreRegistered(String name, ItemStack item) + public void oreRegistered( String name, ItemStack item ) { - if ( !(name.startsWith( "berry" ) || name.startsWith( "nugget" )) ) + if( !( name.startsWith( "berry" ) || name.startsWith( "nugget" ) ) ) return; // addNugget( "Cobble", 18 ); // ? @@ -122,24 +133,15 @@ public class MatterCannonAmmoRegistry implements IOreListener, IMatterCannonAmmo this.considerItem( name, item, "Plutonium", 244 ); // TE stuff... - this.considerItem( name, item, "Invar", (58.6934 + 55.845 + 55.845) / 3.0 ); - this.considerItem( name, item, "Electrum", (107.8682 + 196.96655) / 2.0 ); + this.considerItem( name, item, "Invar", ( 58.6934 + 55.845 + 55.845 ) / 3.0 ); + this.considerItem( name, item, "Electrum", ( 107.8682 + 196.96655 ) / 2.0 ); } - public MatterCannonAmmoRegistry() { - OreDictionaryHandler.INSTANCE.observe( this ); - this.registerAmmo( new ItemStack( Items.gold_nugget ), 196.96655 ); - } - - @Override - public float getPenetration(ItemStack is) + private void considerItem( String ore, ItemStack item, String Name, double weight ) { - for (ItemStack o : this.DamageModifiers.keySet()) + if( ore.equals( "berry" + Name ) || ore.equals( "nugget" + Name ) ) { - if ( Platform.isSameItem( o, is ) ) - return this.DamageModifiers.get( o ).floatValue(); + this.registerAmmo( item, weight ); } - return 0; } - } diff --git a/src/main/java/appeng/core/features/registries/MovableTileRegistry.java b/src/main/java/appeng/core/features/registries/MovableTileRegistry.java index 484eb9c9a..e6d93bdcb 100644 --- a/src/main/java/appeng/core/features/registries/MovableTileRegistry.java +++ b/src/main/java/appeng/core/features/registries/MovableTileRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; @@ -31,6 +32,7 @@ import appeng.api.movable.IMovableRegistry; import appeng.api.movable.IMovableTile; import appeng.spatial.DefaultSpatialHandler; + public class MovableTileRegistry implements IMovableRegistry { @@ -43,14 +45,53 @@ public class MovableTileRegistry implements IMovableRegistry private final IMovableHandler nullHandler = new DefaultSpatialHandler(); - private IMovableHandler testClass(Class myClass, TileEntity te) + @Override + public void blacklistBlock( Block blk ) + { + this.blacklisted.add( blk ); + } + + @Override + public void whiteListTileEntity( Class c ) + { + + if( c.getName().equals( TileEntity.class.getName() ) ) + { + throw new RuntimeException( new AppEngException( "Someone tried to make all tiles movable, this is a clear violation of the purpose of the white list." ) ); + } + + this.test.add( c ); + } + + @Override + public boolean askToMove( TileEntity te ) + { + Class myClass = te.getClass(); + IMovableHandler canMove = this.Valid.get( myClass ); + + if( canMove == null ) + canMove = this.testClass( myClass, te ); + + if( canMove != this.nullHandler ) + { + if( te instanceof IMovableTile ) + ( (IMovableTile) te ).prepareToMove(); + + te.invalidate(); + return true; + } + + return false; + } + + private IMovableHandler testClass( Class myClass, TileEntity te ) { IMovableHandler handler = null; // ask handlers... - for (IMovableHandler han : this.handlers) + for( IMovableHandler han : this.handlers ) { - if ( han.canHandle( myClass, te ) ) + if( han.canHandle( myClass, te ) ) { handler = han; break; @@ -58,24 +99,23 @@ public class MovableTileRegistry implements IMovableRegistry } // if you have a handler your opted in - if ( handler != null ) + if( handler != null ) { this.Valid.put( myClass, handler ); return handler; - } // if your movable our opted in - if ( te instanceof IMovableTile ) + if( te instanceof IMovableTile ) { this.Valid.put( myClass, this.dsh ); return this.dsh; } // if you are on the white list your opted in. - for (Class testClass : this.test) + for( Class testClass : this.test ) { - if ( testClass.isAssignableFrom( myClass ) ) + if( testClass.isAssignableFrom( myClass ) ) { this.Valid.put( myClass, this.dsh ); return this.dsh; @@ -87,30 +127,9 @@ public class MovableTileRegistry implements IMovableRegistry } @Override - public boolean askToMove(TileEntity te) + public void doneMoving( TileEntity te ) { - Class myClass = te.getClass(); - IMovableHandler canMove = this.Valid.get( myClass ); - - if ( canMove == null ) - canMove = this.testClass( myClass, te ); - - if ( canMove != this.nullHandler ) - { - if ( te instanceof IMovableTile ) - ((IMovableTile) te).prepareToMove(); - - te.invalidate(); - return true; - } - - return false; - } - - @Override - public void doneMoving(TileEntity te) - { - if ( te instanceof IMovableTile ) + if( te instanceof IMovableTile ) { IMovableTile mt = (IMovableTile) te; mt.doneMoving(); @@ -118,26 +137,13 @@ public class MovableTileRegistry implements IMovableRegistry } @Override - public void whiteListTileEntity(Class c) - { - - if ( c.getName().equals( TileEntity.class.getName() ) ) - { - throw new RuntimeException( new AppEngException( - "Someone tried to make all tiles movable, this is a clear violation of the purpose of the white list." ) ); - } - - this.test.add( c ); - } - - @Override - public void addHandler(IMovableHandler han) + public void addHandler( IMovableHandler han ) { this.handlers.add( han ); } @Override - public IMovableHandler getHandler(TileEntity te) + public IMovableHandler getHandler( TileEntity te ) { Class myClass = te.getClass(); IMovableHandler h = this.Valid.get( myClass ); @@ -151,15 +157,8 @@ public class MovableTileRegistry implements IMovableRegistry } @Override - public void blacklistBlock(Block blk) - { - this.blacklisted.add( blk ); - } - - @Override - public boolean isBlacklisted(Block blk) + public boolean isBlacklisted( Block blk ) { return this.blacklisted.contains( blk ); } - } diff --git a/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java b/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java index 6ea7bd279..4d055527f 100644 --- a/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java +++ b/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.util.HashMap; import net.minecraft.init.Blocks; @@ -38,22 +39,12 @@ import appeng.api.features.IP2PTunnelRegistry; import appeng.api.util.AEColor; import appeng.util.Platform; + public class P2PTunnelRegistry implements IP2PTunnelRegistry { final HashMap Tunnels = new HashMap(); - public ItemStack getModItem(String modID, String Name, int meta) - { - ItemStack myItemStack = GameRegistry.findItemStack( modID, Name, 1 ); - - if ( myItemStack == null ) - return null; - - myItemStack.setItemDamage( meta ); - return myItemStack; - } - public void configure() { /** @@ -111,7 +102,7 @@ public class P2PTunnelRegistry implements IP2PTunnelRegistry this.addNewAttunement( this.getModItem( "ExtraUtilities", "drum", OreDictionary.WILDCARD_VALUE ), TunnelType.FLUID ); this.addNewAttunement( this.getModItem( "EnderIO", "itemLiquidConduit", OreDictionary.WILDCARD_VALUE ), TunnelType.FLUID ); - for (AEColor c : AEColor.values()) + for( AEColor c : AEColor.values() ) { this.addNewAttunement( parts.cableGlass().stack( c, 1 ), TunnelType.ME ); this.addNewAttunement( parts.cableCovered().stack( c, 1 ), TunnelType.ME ); @@ -120,42 +111,52 @@ public class P2PTunnelRegistry implements IP2PTunnelRegistry } } + @Override + public void addNewAttunement( ItemStack trigger, TunnelType type ) + { + if( type == null || trigger == null ) + return; + + this.Tunnels.put( trigger, type ); + } + + public ItemStack getModItem( String modID, String Name, int meta ) + { + ItemStack myItemStack = GameRegistry.findItemStack( modID, Name, 1 ); + + if( myItemStack == null ) + return null; + + myItemStack.setItemDamage( meta ); + return myItemStack; + } + private void addNewAttunement( IItemDefinition definition, TunnelType type ) { - for ( ItemStack definitionStack : definition.maybeStack( 1 ).asSet() ) + for( ItemStack definitionStack : definition.maybeStack( 1 ).asSet() ) { this.addNewAttunement( definitionStack, type ); } } @Override - public void addNewAttunement(ItemStack trigger, TunnelType type) + public TunnelType getTunnelTypeByItem( ItemStack trigger ) { - if ( type == null || trigger == null ) - return; - - this.Tunnels.put( trigger, type ); - } - - @Override - public TunnelType getTunnelTypeByItem(ItemStack trigger) - { - if ( trigger != null ) + if( trigger != null ) { - if ( FluidContainerRegistry.isContainer( trigger ) ) + if( FluidContainerRegistry.isContainer( trigger ) ) return TunnelType.FLUID; - for (ItemStack is : this.Tunnels.keySet()) + for( ItemStack is : this.Tunnels.keySet() ) { - if ( is.getItem() == trigger.getItem() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) + if( is.getItem() == trigger.getItem() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) return this.Tunnels.get( is ); - if ( Platform.isSameItem( is, trigger ) ) + if( Platform.isSameItem( is, trigger ) ) return this.Tunnels.get( is ); } } return null; } - } diff --git a/src/main/java/appeng/core/features/registries/PlayerRegistry.java b/src/main/java/appeng/core/features/registries/PlayerRegistry.java index 6025ead5e..2708698c4 100644 --- a/src/main/java/appeng/core/features/registries/PlayerRegistry.java +++ b/src/main/java/appeng/core/features/registries/PlayerRegistry.java @@ -18,32 +18,33 @@ package appeng.core.features.registries; -import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; +import com.mojang.authlib.GameProfile; + import appeng.api.features.IPlayerRegistry; import appeng.core.WorldSettings; + public class PlayerRegistry implements IPlayerRegistry { @Override - public int getID(GameProfile username) + public int getID( GameProfile username ) { return WorldSettings.getInstance().getPlayerID( username ); } @Override - public int getID(EntityPlayer player) + public int getID( EntityPlayer player ) { return WorldSettings.getInstance().getPlayerID( player.getGameProfile() ); } @Override - public EntityPlayer findPlayer(int playerID) + public EntityPlayer findPlayer( int playerID ) { return WorldSettings.getInstance().getPlayerFromID( playerID ); } - } diff --git a/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java b/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java index e5a28be7b..a7da1077c 100644 --- a/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java +++ b/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.util.HashMap; import java.util.LinkedList; @@ -28,6 +29,7 @@ import appeng.api.recipes.ISubItemResolver; import appeng.core.AELog; import appeng.recipes.RecipeHandler; + public class RecipeHandlerRegistry implements IRecipeHandlerRegistry { @@ -35,22 +37,28 @@ public class RecipeHandlerRegistry implements IRecipeHandlerRegistry final LinkedList resolvers = new LinkedList(); @Override - public void addNewCraftHandler(String name, Class handler) + public void addNewCraftHandler( String name, Class handler ) { this.handlers.put( name.toLowerCase(), handler ); } @Override - public ICraftHandler getCraftHandlerFor(String name) + public void addNewSubItemResolver( ISubItemResolver sir ) + { + this.resolvers.add( sir ); + } + + @Override + public ICraftHandler getCraftHandlerFor( String name ) { Class clz = this.handlers.get( name ); - if ( clz == null ) + if( clz == null ) return null; try { return clz.newInstance(); } - catch (Throwable e) + catch( Throwable e ) { AELog.severe( "Error Caused when trying to construct " + clz.getName() ); AELog.error( e ); @@ -66,15 +74,9 @@ public class RecipeHandlerRegistry implements IRecipeHandlerRegistry } @Override - public void addNewSubItemResolver(ISubItemResolver sir) + public Object resolveItem( String nameSpace, String itemName ) { - this.resolvers.add( sir ); - } - - @Override - public Object resolveItem(String nameSpace, String itemName) - { - for (ISubItemResolver sir : this.resolvers) + for( ISubItemResolver sir : this.resolvers ) { Object rr = null; @@ -82,16 +84,15 @@ public class RecipeHandlerRegistry implements IRecipeHandlerRegistry { rr = sir.resolveItemByName( nameSpace, itemName ); } - catch (Throwable t) + catch( Throwable t ) { AELog.error( t ); } - if ( rr != null ) + if( rr != null ) return rr; } return null; } - } diff --git a/src/main/java/appeng/core/features/registries/RegistryContainer.java b/src/main/java/appeng/core/features/registries/RegistryContainer.java index a09865f85..3150ae736 100644 --- a/src/main/java/appeng/core/features/registries/RegistryContainer.java +++ b/src/main/java/appeng/core/features/registries/RegistryContainer.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import appeng.api.features.IGrinderRegistry; import appeng.api.features.ILocatableRegistry; import appeng.api.features.IMatterCannonAmmoRegistry; @@ -33,6 +34,7 @@ import appeng.api.networking.IGridCacheRegistry; import appeng.api.storage.ICellRegistry; import appeng.api.storage.IExternalStorageRegistry; + public class RegistryContainer implements IRegistryContainer { @@ -49,6 +51,30 @@ public class RegistryContainer implements IRegistryContainer private final PlayerRegistry playerRegistry = new PlayerRegistry(); private final IRecipeHandlerRegistry recipeReg = new RecipeHandlerRegistry(); + @Override + public IMovableRegistry movable() + { + return this.MovableReg; + } + + @Override + public IGridCacheRegistry gridCache() + { + return this.GridCacheRegistry; + } + + @Override + public IExternalStorageRegistry externalStorage() + { + return this.ExternalStorageHandlers; + } + + @Override + public ISpecialComparisonRegistry specialComparison() + { + return this.SpecialComparisonRegistry; + } + @Override public IWirelessTermRegistry wireless() { @@ -67,36 +93,12 @@ public class RegistryContainer implements IRegistryContainer return this.GrinderRecipes; } - @Override - public ISpecialComparisonRegistry specialComparison() - { - return this.SpecialComparisonRegistry; - } - - @Override - public IExternalStorageRegistry externalStorage() - { - return this.ExternalStorageHandlers; - } - @Override public ILocatableRegistry locatable() { return this.LocatableRegistry; } - @Override - public IGridCacheRegistry gridCache() - { - return this.GridCacheRegistry; - } - - @Override - public IMovableRegistry movable() - { - return this.MovableReg; - } - @Override public IP2PTunnelRegistry p2pTunnel() { @@ -126,5 +128,4 @@ public class RegistryContainer implements IRegistryContainer { return WorldGenRegistry.INSTANCE; } - } diff --git a/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java b/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java index 1fb0a10da..013cb5f15 100644 --- a/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java +++ b/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.util.ArrayList; import java.util.List; @@ -27,22 +28,24 @@ import appeng.api.features.IItemComparison; import appeng.api.features.IItemComparisonProvider; import appeng.api.features.ISpecialComparisonRegistry; + public class SpecialComparisonRegistry implements ISpecialComparisonRegistry { private final List CompRegistry; - public SpecialComparisonRegistry() { + public SpecialComparisonRegistry() + { this.CompRegistry = new ArrayList(); } @Override - public IItemComparison getSpecialComparison(ItemStack stack) + public IItemComparison getSpecialComparison( ItemStack stack ) { - for (IItemComparisonProvider i : this.CompRegistry) + for( IItemComparisonProvider i : this.CompRegistry ) { IItemComparison comp = i.getComparison( stack ); - if ( comp != null ) + if( comp != null ) { return comp; } @@ -52,9 +55,8 @@ public class SpecialComparisonRegistry implements ISpecialComparisonRegistry } @Override - public void addComparisonProvider(IItemComparisonProvider prov) + public void addComparisonProvider( IItemComparisonProvider prov ) { this.CompRegistry.add( prov ); } - } diff --git a/src/main/java/appeng/core/features/registries/WirelessRangeResult.java b/src/main/java/appeng/core/features/registries/WirelessRangeResult.java index 775cea9fe..0e3726955 100644 --- a/src/main/java/appeng/core/features/registries/WirelessRangeResult.java +++ b/src/main/java/appeng/core/features/registries/WirelessRangeResult.java @@ -18,17 +18,19 @@ package appeng.core.features.registries; + import net.minecraft.tileentity.TileEntity; + public class WirelessRangeResult { - public WirelessRangeResult(TileEntity t, float d) { - this.dist = d; - this.te = t; - } - final public float dist; final public TileEntity te; + public WirelessRangeResult( TileEntity t, float d ) + { + this.dist = d; + this.te = t; + } } diff --git a/src/main/java/appeng/core/features/registries/WirelessRegistry.java b/src/main/java/appeng/core/features/registries/WirelessRegistry.java index 656adcc6e..5a9408498 100644 --- a/src/main/java/appeng/core/features/registries/WirelessRegistry.java +++ b/src/main/java/appeng/core/features/registries/WirelessRegistry.java @@ -34,50 +34,52 @@ import appeng.core.localization.PlayerMessages; import appeng.core.sync.GuiBridge; import appeng.util.Platform; + public final class WirelessRegistry implements IWirelessTermRegistry { private final List handlers; - public WirelessRegistry() { + public WirelessRegistry() + { this.handlers = new ArrayList(); } @Override - public void registerWirelessHandler(IWirelessTermHandler handler) + public void registerWirelessHandler( IWirelessTermHandler handler ) { - if ( handler != null ) + if( handler != null ) this.handlers.add( handler ); } @Override - public boolean isWirelessTerminal(ItemStack is) + public boolean isWirelessTerminal( ItemStack is ) { - for (IWirelessTermHandler h : this.handlers) + for( IWirelessTermHandler h : this.handlers ) { - if ( h.canHandle( is ) ) + if( h.canHandle( is ) ) return true; } return false; } @Override - public IWirelessTermHandler getWirelessTerminalHandler(ItemStack is) + public IWirelessTermHandler getWirelessTerminalHandler( ItemStack is ) { - for (IWirelessTermHandler h : this.handlers) + for( IWirelessTermHandler h : this.handlers ) { - if ( h.canHandle( is ) ) + if( h.canHandle( is ) ) return h; } return null; } @Override - public void openWirelessTerminalGui(ItemStack item, World w, EntityPlayer player) + public void openWirelessTerminalGui( ItemStack item, World w, EntityPlayer player ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; - if ( !this.isWirelessTerminal( item ) ) + if( !this.isWirelessTerminal( item ) ) { player.addChatMessage( PlayerMessages.DeviceNotWirelessTerminal.get() ); return; @@ -85,7 +87,7 @@ public final class WirelessRegistry implements IWirelessTermRegistry final IWirelessTermHandler handler = this.getWirelessTerminalHandler( item ); final String unparsedKey = handler.getEncryptionKey( item ); - if ( unparsedKey.length() == 0 ) + if( unparsedKey.length() == 0 ) { player.addChatMessage( PlayerMessages.DeviceNotLinked.get() ); return; @@ -93,19 +95,17 @@ public final class WirelessRegistry implements IWirelessTermRegistry final long parsedKey = Long.parseLong( unparsedKey ); final ILocatable securityStation = AEApi.instance().registries().locatable().getLocatableBy( parsedKey ); - if ( securityStation == null ) + if( securityStation == null ) { player.addChatMessage( PlayerMessages.StationCanNotBeLocated.get() ); return; } - if ( handler.hasPower( player, 0.5, item ) ) + if( handler.hasPower( player, 0.5, item ) ) { Platform.openGUI( player, null, null, GuiBridge.GUI_WIRELESS_TERM ); } else player.addChatMessage( PlayerMessages.DeviceNotPowered.get() ); - } - } diff --git a/src/main/java/appeng/core/features/registries/WorldGenRegistry.java b/src/main/java/appeng/core/features/registries/WorldGenRegistry.java index a64006383..4d14df702 100644 --- a/src/main/java/appeng/core/features/registries/WorldGenRegistry.java +++ b/src/main/java/appeng/core/features/registries/WorldGenRegistry.java @@ -18,6 +18,7 @@ package appeng.core.features.registries; + import java.util.HashSet; import net.minecraft.world.World; @@ -25,75 +26,49 @@ import net.minecraft.world.WorldProvider; import appeng.api.features.IWorldGen; + public final class WorldGenRegistry implements IWorldGen { - private static class TypeSet - { - - final HashSet> badProviders = new HashSet>(); - final HashSet badDimensions = new HashSet(); - final HashSet enabledDimensions = new HashSet(); - - } - + static final public WorldGenRegistry INSTANCE = new WorldGenRegistry(); final TypeSet[] types; - static final public WorldGenRegistry INSTANCE = new WorldGenRegistry(); - - private WorldGenRegistry() { + private WorldGenRegistry() + { this.types = new TypeSet[WorldGenType.values().length]; - for (WorldGenType type : WorldGenType.values()) + for( WorldGenType type : WorldGenType.values() ) { this.types[type.ordinal()] = new TypeSet(); } - } @Override - public boolean isWorldGenEnabled(WorldGenType type, World w) + public void disableWorldGenForProviderID( WorldGenType type, Class provider ) { - if ( type == null ) + if( type == null ) throw new IllegalArgumentException( "Bad Type Passed" ); - if ( w == null ) - throw new IllegalArgumentException( "Bad Provider Passed" ); - - boolean isBadProvider = this.types[type.ordinal()].badProviders.contains( w.provider.getClass() ); - boolean isBadDimension = this.types[type.ordinal()].badDimensions.contains( w.provider.dimensionId ); - boolean isGoodDimension = this.types[type.ordinal()].enabledDimensions.contains( w.provider.dimensionId ); - - if ( isBadProvider || isBadDimension ) - { - return false; - } - - if ( !isGoodDimension && type == WorldGenType.Meteorites) - { - return false; - } - - return true; - } - - @Override - public void disableWorldGenForProviderID(WorldGenType type, Class provider) - { - if ( type == null ) - throw new IllegalArgumentException( "Bad Type Passed" ); - - if ( provider == null ) + if( provider == null ) throw new IllegalArgumentException( "Bad Provider Passed" ); this.types[type.ordinal()].badProviders.add( provider ); } @Override - public void disableWorldGenForDimension(WorldGenType type, int dimensionID) + public void enableWorldGenForDimension( WorldGenType type, int dimensionID ) { - if ( type == null ) + if( type == null ) + throw new IllegalArgumentException( "Bad Type Passed" ); + + this.types[type.ordinal()].enabledDimensions.add( dimensionID ); + } + + @Override + public void disableWorldGenForDimension( WorldGenType type, int dimensionID ) + { + if( type == null ) { throw new IllegalArgumentException( "Bad Type Passed" ); } @@ -102,12 +77,36 @@ public final class WorldGenRegistry implements IWorldGen } @Override - public void enableWorldGenForDimension(WorldGenType type, int dimensionID) + public boolean isWorldGenEnabled( WorldGenType type, World w ) { - if ( type == null ) + if( type == null ) throw new IllegalArgumentException( "Bad Type Passed" ); - this.types[type.ordinal()].enabledDimensions.add( dimensionID ); + if( w == null ) + throw new IllegalArgumentException( "Bad Provider Passed" ); + + boolean isBadProvider = this.types[type.ordinal()].badProviders.contains( w.provider.getClass() ); + boolean isBadDimension = this.types[type.ordinal()].badDimensions.contains( w.provider.dimensionId ); + boolean isGoodDimension = this.types[type.ordinal()].enabledDimensions.contains( w.provider.dimensionId ); + + if( isBadProvider || isBadDimension ) + { + return false; + } + + if( !isGoodDimension && type == WorldGenType.Meteorites ) + { + return false; + } + + return true; } + private static class TypeSet + { + + final HashSet> badProviders = new HashSet>(); + final HashSet badDimensions = new HashSet(); + final HashSet enabledDimensions = new HashSet(); + } } diff --git a/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java b/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java index 1cd2e921a..e88e0ce5f 100644 --- a/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java +++ b/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java @@ -18,10 +18,12 @@ package appeng.core.features.registries.entries; + import net.minecraft.item.ItemStack; import appeng.api.features.IGrinderEntry; + public class AppEngGrinderRecipe implements IGrinderEntry { @@ -36,13 +38,15 @@ public class AppEngGrinderRecipe implements IGrinderEntry private int energy; - public AppEngGrinderRecipe(ItemStack a, ItemStack b, int cost) { + public AppEngGrinderRecipe( ItemStack a, ItemStack b, int cost ) + { this.in = a; this.out = b; this.energy = cost; } - public AppEngGrinderRecipe(ItemStack a, ItemStack b, ItemStack c, float chance, int cost) { + public AppEngGrinderRecipe( ItemStack a, ItemStack b, ItemStack c, float chance, int cost ) + { this.in = a; this.out = b; @@ -52,7 +56,8 @@ public class AppEngGrinderRecipe implements IGrinderEntry this.energy = cost; } - public AppEngGrinderRecipe(ItemStack a, ItemStack b, ItemStack c, ItemStack d, float chance, float chance2, int cost) { + public AppEngGrinderRecipe( ItemStack a, ItemStack b, ItemStack c, ItemStack d, float chance, float chance2, int cost ) + { this.in = a; this.out = b; @@ -72,7 +77,7 @@ public class AppEngGrinderRecipe implements IGrinderEntry } @Override - public void setInput(ItemStack i) + public void setInput( ItemStack i ) { this.in = i.copy(); } @@ -84,23 +89,11 @@ public class AppEngGrinderRecipe implements IGrinderEntry } @Override - public void setOutput(ItemStack o) + public void setOutput( ItemStack o ) { this.out = o.copy(); } - @Override - public int getEnergyCost() - { - return this.energy; - } - - @Override - public void setEnergyCost(int c) - { - this.energy = c; - } - @Override public ItemStack getOptionalOutput() { @@ -108,7 +101,13 @@ public class AppEngGrinderRecipe implements IGrinderEntry } @Override - public void setOptionalOutput(ItemStack output, float chance) + public ItemStack getSecondOptionalOutput() + { + return this.optionalOutput2; + } + + @Override + public void setOptionalOutput( ItemStack output, float chance ) { this.optionalOutput = output.copy(); this.optionalChance = chance; @@ -121,13 +120,7 @@ public class AppEngGrinderRecipe implements IGrinderEntry } @Override - public ItemStack getSecondOptionalOutput() - { - return this.optionalOutput2; - } - - @Override - public void setSecondOptionalOutput(ItemStack output, float chance) + public void setSecondOptionalOutput( ItemStack output, float chance ) { this.optionalChance2 = chance; this.optionalOutput2 = output.copy(); @@ -139,4 +132,15 @@ public class AppEngGrinderRecipe implements IGrinderEntry return this.optionalChance2; } + @Override + public int getEnergyCost() + { + return this.energy; + } + + @Override + public void setEnergyCost( int c ) + { + this.energy = c; + } } diff --git a/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java b/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java index de287dbe3..d26592408 100644 --- a/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java +++ b/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java @@ -18,6 +18,7 @@ package appeng.core.features.registries.entries; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; @@ -37,29 +38,24 @@ import appeng.me.storage.CellInventoryHandler; import appeng.tile.AEBaseTile; import appeng.util.Platform; + public class BasicCellHandler implements ICellHandler { @Override - public boolean isCell(ItemStack is) + public boolean isCell( ItemStack is ) { return CellInventory.isCell( is ); } @Override - public IMEInventoryHandler getCellInventory(ItemStack is, ISaveProvider container, StorageChannel channel) + public IMEInventoryHandler getCellInventory( ItemStack is, ISaveProvider container, StorageChannel channel ) { - if ( channel == StorageChannel.ITEMS ) + if( channel == StorageChannel.ITEMS ) return CellInventory.getCell( is, container ); return null; } - @Override - public IIcon getTopTexture_Dark() - { - return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); - } - @Override public IIcon getTopTexture_Light() { @@ -73,15 +69,21 @@ public class BasicCellHandler implements ICellHandler } @Override - public void openChestGui(EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan) + public IIcon getTopTexture_Dark() + { + return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); + } + + @Override + public void openChestGui( EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan ) { Platform.openGUI( player, (AEBaseTile) chest, chest.getUp(), GuiBridge.GUI_ME ); } @Override - public int getStatusForCell(ItemStack is, IMEInventory handler) + public int getStatusForCell( ItemStack is, IMEInventory handler ) { - if ( handler instanceof CellInventoryHandler ) + if( handler instanceof CellInventoryHandler ) { CellInventoryHandler ci = (CellInventoryHandler) handler; return ci.getStatusForCell(); @@ -90,9 +92,9 @@ public class BasicCellHandler implements ICellHandler } @Override - public double cellIdleDrain(ItemStack is, IMEInventory handler) + public double cellIdleDrain( ItemStack is, IMEInventory handler ) { - ICellInventory inv = ((ICellInventoryHandler) handler).getCellInv(); + ICellInventory inv = ( (ICellInventoryHandler) handler ).getCellInv(); return inv.getIdleDrain(); } } diff --git a/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java b/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java index 34449fa97..9fc1ec009 100644 --- a/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java +++ b/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java @@ -18,6 +18,7 @@ package appeng.core.features.registries.entries; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; @@ -35,41 +36,24 @@ import appeng.me.storage.CreativeCellInventory; import appeng.tile.AEBaseTile; import appeng.util.Platform; + public class CreativeCellHandler implements ICellHandler { @Override - public boolean isCell(ItemStack is) + public boolean isCell( ItemStack is ) { return is != null && is.getItem() instanceof ItemCreativeStorageCell; } @Override - public IMEInventoryHandler getCellInventory(ItemStack is, ISaveProvider container, StorageChannel channel) + public IMEInventoryHandler getCellInventory( ItemStack is, ISaveProvider container, StorageChannel channel ) { - if ( channel == StorageChannel.ITEMS && is != null && is.getItem() instanceof ItemCreativeStorageCell ) + if( channel == StorageChannel.ITEMS && is != null && is.getItem() instanceof ItemCreativeStorageCell ) return CreativeCellInventory.getCell( is ); return null; } - @Override - public void openChestGui(EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan) - { - Platform.openGUI( player, (AEBaseTile) chest, chest.getUp(), GuiBridge.GUI_ME ); - } - - @Override - public int getStatusForCell(ItemStack is, IMEInventory handler) - { - return 2; - } - - @Override - public double cellIdleDrain(ItemStack is, IMEInventory handler) - { - return 0; - } - @Override public IIcon getTopTexture_Light() { @@ -88,4 +72,21 @@ public class CreativeCellHandler implements ICellHandler return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); } + @Override + public void openChestGui( EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan ) + { + Platform.openGUI( player, (AEBaseTile) chest, chest.getUp(), GuiBridge.GUI_ME ); + } + + @Override + public int getStatusForCell( ItemStack is, IMEInventory handler ) + { + return 2; + } + + @Override + public double cellIdleDrain( ItemStack is, IMEInventory handler ) + { + return 0; + } } diff --git a/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java b/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java index 035a0cd82..452a5c577 100644 --- a/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java +++ b/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java @@ -18,6 +18,7 @@ package appeng.core.features.registries.entries; + import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -29,24 +30,24 @@ import appeng.api.storage.StorageChannel; import appeng.me.storage.MEMonitorIInventory; import appeng.util.InventoryAdaptor; + public class ExternalIInv implements IExternalStorageHandler { @Override - public boolean canHandle(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc) + public boolean canHandle( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc ) { return channel == StorageChannel.ITEMS && te instanceof IInventory; } @Override - public IMEInventory getInventory(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src) + public IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src ) { InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, d ); - if ( channel == StorageChannel.ITEMS && ad != null ) + if( channel == StorageChannel.ITEMS && ad != null ) return new MEMonitorIInventory( ad ); return null; } - } diff --git a/src/main/java/appeng/core/localization/ButtonToolTips.java b/src/main/java/appeng/core/localization/ButtonToolTips.java index 9c1a4339b..ad1c51b96 100644 --- a/src/main/java/appeng/core/localization/ButtonToolTips.java +++ b/src/main/java/appeng/core/localization/ButtonToolTips.java @@ -72,14 +72,14 @@ public enum ButtonToolTips this.root = r; } - public String getUnlocalized() - { - return this.root + '.' + this.toString(); - } - public String getLocal() { return StatCollector.translateToLocal( this.getUnlocalized() ); } + public String getUnlocalized() + { + return this.root + '.' + this.toString(); + } + } diff --git a/src/main/java/appeng/core/localization/GuiText.java b/src/main/java/appeng/core/localization/GuiText.java index 958d33830..9b51d7e90 100644 --- a/src/main/java/appeng/core/localization/GuiText.java +++ b/src/main/java/appeng/core/localization/GuiText.java @@ -18,11 +18,13 @@ package appeng.core.localization; + import net.minecraft.util.StatCollector; + public enum GuiText { - inventory("container"), // mc's default Inventory localization. + inventory( "container" ), // mc's default Inventory localization. Chest, StoredEnergy, Of, Condenser, Drive, GrindStone, SkyChest, @@ -72,17 +74,14 @@ public enum GuiText final String root; - GuiText() { + GuiText() + { this.root = "gui.appliedenergistics2"; } - GuiText(String r) { - this.root = r; - } - - public String getUnlocalized() + GuiText( String r ) { - return this.root + '.' + this.toString(); + this.root = r; } public String getLocal() @@ -90,4 +89,9 @@ public enum GuiText return StatCollector.translateToLocal( this.getUnlocalized() ); } + public String getUnlocalized() + { + return this.root + '.' + this.toString(); + } + } diff --git a/src/main/java/appeng/core/localization/PlayerMessages.java b/src/main/java/appeng/core/localization/PlayerMessages.java index c98f7285d..412a8e61e 100644 --- a/src/main/java/appeng/core/localization/PlayerMessages.java +++ b/src/main/java/appeng/core/localization/PlayerMessages.java @@ -18,9 +18,11 @@ package appeng.core.localization; + import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; + public enum PlayerMessages { ChestCannotReadStorageCell, InvalidMachine, LoadedSettings, SavedSettings, MachineNotPowered, @@ -30,14 +32,14 @@ public enum PlayerMessages CommunicationError, OutOfRange, DeviceNotPowered, DeviceNotWirelessTerminal, DeviceNotLinked, StationCanNotBeLocated, SettingCleared,; - String getName() - { - return "chat.appliedenergistics2." + this.toString(); - } - public IChatComponent get() { return new ChatComponentTranslation( this.getName() ); } + String getName() + { + return "chat.appliedenergistics2." + this.toString(); + } + } diff --git a/src/main/java/appeng/core/localization/WailaText.java b/src/main/java/appeng/core/localization/WailaText.java index d1b8a6531..bfcc5f046 100644 --- a/src/main/java/appeng/core/localization/WailaText.java +++ b/src/main/java/appeng/core/localization/WailaText.java @@ -18,8 +18,10 @@ package appeng.core.localization; + import net.minecraft.util.StatCollector; + public enum WailaText { Crafting, @@ -32,17 +34,14 @@ public enum WailaText final String root; - WailaText() { + WailaText() + { this.root = "waila.appliedenergistics2"; } - WailaText(String r) { - this.root = r; - } - - public String getUnlocalized() + WailaText( String r ) { - return this.root + '.' + this.toString(); + this.root = r; } public String getLocal() @@ -50,4 +49,9 @@ public enum WailaText return StatCollector.translateToLocal( this.getUnlocalized() ); } + public String getUnlocalized() + { + return this.root + '.' + this.toString(); + } + } diff --git a/src/main/java/appeng/core/settings/TickRates.java b/src/main/java/appeng/core/settings/TickRates.java index 93d18ed64..8fa6daf4d 100644 --- a/src/main/java/appeng/core/settings/TickRates.java +++ b/src/main/java/appeng/core/settings/TickRates.java @@ -18,48 +18,49 @@ package appeng.core.settings; + import appeng.core.AEConfig; + public enum TickRates { - Interface(5, 120), + Interface( 5, 120 ), - ImportBus(5, 40), + ImportBus( 5, 40 ), - ExportBus(5, 60), + ExportBus( 5, 60 ), - AnnihilationPlane(2, 120), + AnnihilationPlane( 2, 120 ), - MJTunnel(1, 20), + MJTunnel( 1, 20 ), - METunnel(5, 20), + METunnel( 5, 20 ), - Inscriber(1, 1), + Inscriber( 1, 1 ), - IOPort(1, 5), + IOPort( 1, 5 ), - VibrationChamber(10, 40), + VibrationChamber( 10, 40 ), - StorageBus(5, 60), + StorageBus( 5, 60 ), - ItemTunnel(5, 60), + ItemTunnel( 5, 60 ), - LightTunnel(5, 120); + LightTunnel( 5, 120 ); public int min; public int max; - TickRates( int min, int max ) { + TickRates( int min, int max ) + { this.min = min; this.max = max; } - public void Load(AEConfig config) + public void Load( AEConfig config ) { - config.addCustomCategoryComment( - "TickRates", - " Min / Max Tickrates for dynamic ticking, most of these components also use sleeping, to prevent constant ticking, adjust with care, non standard rates are not supported or tested." ); + config.addCustomCategoryComment( "TickRates", " Min / Max Tickrates for dynamic ticking, most of these components also use sleeping, to prevent constant ticking, adjust with care, non standard rates are not supported or tested." ); this.min = config.get( "TickRates", this.name() + ".min", this.min ).getInt( this.min ); this.max = config.get( "TickRates", this.name() + ".max", this.max ).getInt( this.max ); } diff --git a/src/main/java/appeng/core/stats/AchievementCraftingHandler.java b/src/main/java/appeng/core/stats/AchievementCraftingHandler.java index 32f21f3f2..20143637c 100644 --- a/src/main/java/appeng/core/stats/AchievementCraftingHandler.java +++ b/src/main/java/appeng/core/stats/AchievementCraftingHandler.java @@ -44,22 +44,22 @@ public class AchievementCraftingHandler @SubscribeEvent public void onPlayerCraftingEvent( PlayerEvent.ItemCraftedEvent event ) { - if ( this.differentiator.isNoPlayer( event.player ) || event.crafting == null ) + if( this.differentiator.isNoPlayer( event.player ) || event.crafting == null ) return; - for ( Achievements achievement : Achievements.values() ) + for( Achievements achievement : Achievements.values() ) { - switch ( achievement.type ) + switch( achievement.type ) { case Craft: - if ( Platform.isSameItemPrecise( achievement.stack, event.crafting ) ) + if( Platform.isSameItemPrecise( achievement.stack, event.crafting ) ) { achievement.addToPlayer( event.player ); return; } break; case CraftItem: - if ( achievement.stack != null && achievement.stack.getItem().getClass() == event.crafting.getItem().getClass() ) + if( achievement.stack != null && achievement.stack.getItem().getClass() == event.crafting.getItem().getClass() ) { achievement.addToPlayer( event.player ); return; diff --git a/src/main/java/appeng/core/stats/AchievementPickupHandler.java b/src/main/java/appeng/core/stats/AchievementPickupHandler.java index 29dfbd388..1e757632d 100644 --- a/src/main/java/appeng/core/stats/AchievementPickupHandler.java +++ b/src/main/java/appeng/core/stats/AchievementPickupHandler.java @@ -46,14 +46,14 @@ public class AchievementPickupHandler @SubscribeEvent public void onItemPickUp( PlayerEvent.ItemPickupEvent event ) { - if ( this.differentiator.isNoPlayer( event.player ) || event.pickedUp == null || event.pickedUp.getEntityItem() == null ) + if( this.differentiator.isNoPlayer( event.player ) || event.pickedUp == null || event.pickedUp.getEntityItem() == null ) return; ItemStack is = event.pickedUp.getEntityItem(); - for ( Achievements achievement : Achievements.values() ) + for( Achievements achievement : Achievements.values() ) { - if ( achievement.type == AchievementType.Pickup && Platform.isSameItemPrecise( achievement.stack, is ) ) + if( achievement.type == AchievementType.Pickup && Platform.isSameItemPrecise( achievement.stack, is ) ) { achievement.addToPlayer( event.player ); return; diff --git a/src/main/java/appeng/core/stats/AchievementType.java b/src/main/java/appeng/core/stats/AchievementType.java index ba6397239..2e90ba9ca 100644 --- a/src/main/java/appeng/core/stats/AchievementType.java +++ b/src/main/java/appeng/core/stats/AchievementType.java @@ -18,6 +18,7 @@ package appeng.core.stats; + public enum AchievementType { diff --git a/src/main/java/appeng/core/stats/Achievements.java b/src/main/java/appeng/core/stats/Achievements.java index 2159c2d8a..047c1ac28 100644 --- a/src/main/java/appeng/core/stats/Achievements.java +++ b/src/main/java/appeng/core/stats/Achievements.java @@ -114,25 +114,9 @@ public enum Achievements private Achievement parent; private Achievement stat; - public void setParent( Achievements parent ) - { - this.parent = parent.getAchievement(); - } - - public Achievement getAchievement() - { - if ( this.stat == null && this.stack != null ) - { - this.stat = new Achievement( "achievement.ae2." + this.name(), "ae2." + this.name(), this.x, this.y, this.stack, this.parent ); - this.stat.registerStat(); - } - - return this.stat; - } - Achievements( int x, int y, AEColoredItemDefinition which, AchievementType type ) { - this.stack = (which != null) ? which.stack( AEColor.Transparent, 1 ) : null; + this.stack = ( which != null ) ? which.stack( AEColor.Transparent, 1 ) : null; this.type = type; this.x = x; this.y = y; @@ -154,6 +138,22 @@ public enum Achievements this.y = y; } + public void setParent( Achievements parent ) + { + this.parent = parent.getAchievement(); + } + + public Achievement getAchievement() + { + if( this.stat == null && this.stack != null ) + { + this.stat = new Achievement( "achievement.ae2." + this.name(), "ae2." + this.name(), this.x, this.y, this.stack, this.parent ); + this.stat.registerStat(); + } + + return this.stat; + } + public void addToPlayer( EntityPlayer player ) { player.addStat( this.getAchievement(), 1 ); diff --git a/src/main/java/appeng/core/stats/PlayerDifferentiator.java b/src/main/java/appeng/core/stats/PlayerDifferentiator.java index ebb7d92c7..04a583233 100644 --- a/src/main/java/appeng/core/stats/PlayerDifferentiator.java +++ b/src/main/java/appeng/core/stats/PlayerDifferentiator.java @@ -38,7 +38,8 @@ public class PlayerDifferentiator * - dead * - fake * - * @param player to be checked player + * @param player to be checked player + * * @return true if {@param player} is not a real player */ public boolean isNoPlayer( EntityPlayer player ) diff --git a/src/main/java/appeng/core/stats/PlayerStatsRegistration.java b/src/main/java/appeng/core/stats/PlayerStatsRegistration.java index 226271c9e..67c87662c 100644 --- a/src/main/java/appeng/core/stats/PlayerStatsRegistration.java +++ b/src/main/java/appeng/core/stats/PlayerStatsRegistration.java @@ -64,7 +64,7 @@ public class PlayerStatsRegistration */ public void registerAchievementHandlers() { - if ( this.isAchievementFeatureEnabled ) + if( this.isAchievementFeatureEnabled ) { final PlayerDifferentiator differentiator = new PlayerDifferentiator(); final AchievementCraftingHandler craftingHandler = new AchievementCraftingHandler( differentiator ); @@ -80,12 +80,12 @@ public class PlayerStatsRegistration */ public void registerAchievements() { - if ( this.isAchievementFeatureEnabled ) + if( this.isAchievementFeatureEnabled ) { final AchievementHierarchy hierarchy = new AchievementHierarchy(); hierarchy.registerAchievementHierarchy(); - for ( Stats s : Stats.values() ) + for( Stats s : Stats.values() ) s.getStat(); /** @@ -93,10 +93,10 @@ public class PlayerStatsRegistration */ ArrayList list = new ArrayList(); - for ( Achievements a : Achievements.values() ) + for( Achievements a : Achievements.values() ) { Achievement ach = a.getAchievement(); - if ( ach != null ) + if( ach != null ) list.add( ach ); } diff --git a/src/main/java/appeng/core/stats/Stats.java b/src/main/java/appeng/core/stats/Stats.java index ea2e88471..ab076ba64 100644 --- a/src/main/java/appeng/core/stats/Stats.java +++ b/src/main/java/appeng/core/stats/Stats.java @@ -18,10 +18,12 @@ package appeng.core.stats; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.stats.StatBasic; import net.minecraft.util.ChatComponentTranslation; + public enum Stats { @@ -36,9 +38,18 @@ public enum Stats private StatBasic stat; + Stats() + { + } + + public void addToPlayer( EntityPlayer player, int howMany ) + { + player.addStat( this.getStat(), howMany ); + } + public StatBasic getStat() { - if ( this.stat == null ) + if( this.stat == null ) { this.stat = new StatBasic( "stat.ae2." + this.name(), new ChatComponentTranslation( "stat.ae2." + this.name() ) ); this.stat.registerStat(); @@ -47,12 +58,4 @@ public enum Stats return this.stat; } - Stats() { - } - - public void addToPlayer(EntityPlayer player, int howMany) - { - player.addStat( this.getStat(), howMany ); - } - } diff --git a/src/main/java/appeng/core/sync/AppEngPacket.java b/src/main/java/appeng/core/sync/AppEngPacket.java index b1ff08d79..1cda7fbc9 100644 --- a/src/main/java/appeng/core/sync/AppEngPacket.java +++ b/src/main/java/appeng/core/sync/AppEngPacket.java @@ -18,6 +18,7 @@ package appeng.core.sync; + import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; @@ -30,29 +31,29 @@ import appeng.core.features.AEFeature; import appeng.core.sync.network.INetworkInfo; import appeng.core.sync.network.NetworkHandler; + public abstract class AppEngPacket { + AppEngPacketHandlerBase.PacketTypes id; private ByteBuf p; - AppEngPacketHandlerBase.PacketTypes id; + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + throw new RuntimeException( "This packet ( " + this.getPacketID() + " does not implement a server side handler." ); + } final public int getPacketID() { return AppEngPacketHandlerBase.PacketTypes.getID( this.getClass() ).ordinal(); } - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - throw new RuntimeException( "This packet ( " + this.getPacketID() + " does not implement a server side handler." ); - } - - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) { throw new RuntimeException( "This packet ( " + this.getPacketID() + " does not implement a client side handler." ); } - protected void configureWrite(ByteBuf data) + protected void configureWrite( ByteBuf data ) { data.capacity( data.readableBytes() ); this.p = data; @@ -60,15 +61,14 @@ public abstract class AppEngPacket public FMLProxyPacket getProxy() { - if ( this.p.array().length > 2 * 1024 * 1024 ) // 2k walking room :) + if( this.p.array().length > 2 * 1024 * 1024 ) // 2k walking room :) throw new IllegalArgumentException( "Sorry AE2 made a " + this.p.array().length + " byte packet by accident!" ); FMLProxyPacket pp = new FMLProxyPacket( this.p, NetworkHandler.instance.getChannel() ); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.PacketLogging ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.PacketLogging ) ) AELog.info( this.getClass().getName() + " : " + pp.payload().readableBytes() ); return pp; } - } diff --git a/src/main/java/appeng/core/sync/GuiBridge.java b/src/main/java/appeng/core/sync/GuiBridge.java index 927b3d394..28b591d1b 100644 --- a/src/main/java/appeng/core/sync/GuiBridge.java +++ b/src/main/java/appeng/core/sync/GuiBridge.java @@ -123,116 +123,120 @@ import static appeng.core.sync.GuiHostType.ITEM; import static appeng.core.sync.GuiHostType.ITEM_OR_WORLD; import static appeng.core.sync.GuiHostType.WORLD; + public enum GuiBridge implements IGuiHandler { GUI_Handler(), - GUI_GRINDER(ContainerGrinder.class, TileGrinder.class, WORLD, null), + GUI_GRINDER( ContainerGrinder.class, TileGrinder.class, WORLD, null ), - GUI_QNB(ContainerQNB.class, TileQuantumBridge.class, WORLD, SecurityPermissions.BUILD), + GUI_QNB( ContainerQNB.class, TileQuantumBridge.class, WORLD, SecurityPermissions.BUILD ), - GUI_SKYCHEST(ContainerSkyChest.class, TileSkyChest.class, WORLD, null), + GUI_SKYCHEST( ContainerSkyChest.class, TileSkyChest.class, WORLD, null ), - GUI_CHEST(ContainerChest.class, TileChest.class, WORLD, SecurityPermissions.BUILD), + GUI_CHEST( ContainerChest.class, TileChest.class, WORLD, SecurityPermissions.BUILD ), - GUI_WIRELESS(ContainerWireless.class, TileWireless.class, WORLD, SecurityPermissions.BUILD), + GUI_WIRELESS( ContainerWireless.class, TileWireless.class, WORLD, SecurityPermissions.BUILD ), - GUI_ME(ContainerMEMonitorable.class, ITerminalHost.class, WORLD, null), + GUI_ME( ContainerMEMonitorable.class, ITerminalHost.class, WORLD, null ), - GUI_PORTABLE_CELL(ContainerMEPortableCell.class, IPortableCell.class, ITEM, null), + GUI_PORTABLE_CELL( ContainerMEPortableCell.class, IPortableCell.class, ITEM, null ), - GUI_WIRELESS_TERM(ContainerWirelessTerm.class, WirelessTerminalGuiObject.class, ITEM, null), + GUI_WIRELESS_TERM( ContainerWirelessTerm.class, WirelessTerminalGuiObject.class, ITEM, null ), - GUI_NETWORK_STATUS(ContainerNetworkStatus.class, INetworkTool.class, ITEM, null), + GUI_NETWORK_STATUS( ContainerNetworkStatus.class, INetworkTool.class, ITEM, null ), - GUI_CRAFTING_CPU(ContainerCraftingCPU.class, TileCraftingTile.class, WORLD, SecurityPermissions.CRAFT), + GUI_CRAFTING_CPU( ContainerCraftingCPU.class, TileCraftingTile.class, WORLD, SecurityPermissions.CRAFT ), - GUI_NETWORK_TOOL(ContainerNetworkTool.class, INetworkTool.class, ITEM, null), + GUI_NETWORK_TOOL( ContainerNetworkTool.class, INetworkTool.class, ITEM, null ), - GUI_QUARTZ_KNIFE(ContainerQuartzKnife.class, QuartzKnifeObj.class, ITEM, null), + GUI_QUARTZ_KNIFE( ContainerQuartzKnife.class, QuartzKnifeObj.class, ITEM, null ), - GUI_DRIVE(ContainerDrive.class, TileDrive.class, WORLD, SecurityPermissions.BUILD), + GUI_DRIVE( ContainerDrive.class, TileDrive.class, WORLD, SecurityPermissions.BUILD ), - GUI_VIBRATION_CHAMBER(ContainerVibrationChamber.class, TileVibrationChamber.class, WORLD, null), + GUI_VIBRATION_CHAMBER( ContainerVibrationChamber.class, TileVibrationChamber.class, WORLD, null ), - GUI_CONDENSER(ContainerCondenser.class, TileCondenser.class, WORLD, null), + GUI_CONDENSER( ContainerCondenser.class, TileCondenser.class, WORLD, null ), - GUI_INTERFACE(ContainerInterface.class, IInterfaceHost.class, WORLD, SecurityPermissions.BUILD), + GUI_INTERFACE( ContainerInterface.class, IInterfaceHost.class, WORLD, SecurityPermissions.BUILD ), - GUI_BUS(ContainerUpgradeable.class, IUpgradeableHost.class, WORLD, SecurityPermissions.BUILD), + GUI_BUS( ContainerUpgradeable.class, IUpgradeableHost.class, WORLD, SecurityPermissions.BUILD ), - GUI_IOPORT(ContainerIOPort.class, TileIOPort.class, WORLD, SecurityPermissions.BUILD), + GUI_IOPORT( ContainerIOPort.class, TileIOPort.class, WORLD, SecurityPermissions.BUILD ), - GUI_STORAGEBUS(ContainerStorageBus.class, PartStorageBus.class, WORLD, SecurityPermissions.BUILD), + GUI_STORAGEBUS( ContainerStorageBus.class, PartStorageBus.class, WORLD, SecurityPermissions.BUILD ), - GUI_FORMATION_PLANE(ContainerFormationPlane.class, PartFormationPlane.class, WORLD, SecurityPermissions.BUILD), + GUI_FORMATION_PLANE( ContainerFormationPlane.class, PartFormationPlane.class, WORLD, SecurityPermissions.BUILD ), - GUI_PRIORITY(ContainerPriority.class, IPriorityHost.class, WORLD, SecurityPermissions.BUILD), + GUI_PRIORITY( ContainerPriority.class, IPriorityHost.class, WORLD, SecurityPermissions.BUILD ), - GUI_SECURITY(ContainerSecurity.class, TileSecurity.class, WORLD, SecurityPermissions.SECURITY), + GUI_SECURITY( ContainerSecurity.class, TileSecurity.class, WORLD, SecurityPermissions.SECURITY ), - GUI_CRAFTING_TERMINAL(ContainerCraftingTerm.class, PartCraftingTerminal.class, WORLD, SecurityPermissions.CRAFT), + GUI_CRAFTING_TERMINAL( ContainerCraftingTerm.class, PartCraftingTerminal.class, WORLD, SecurityPermissions.CRAFT ), - GUI_PATTERN_TERMINAL(ContainerPatternTerm.class, PartPatternTerminal.class, WORLD, SecurityPermissions.CRAFT), + GUI_PATTERN_TERMINAL( ContainerPatternTerm.class, PartPatternTerminal.class, WORLD, SecurityPermissions.CRAFT ), // extends (Container/Gui) + Bus - GUI_LEVEL_EMITTER(ContainerLevelEmitter.class, PartLevelEmitter.class, WORLD, SecurityPermissions.BUILD), + GUI_LEVEL_EMITTER( ContainerLevelEmitter.class, PartLevelEmitter.class, WORLD, SecurityPermissions.BUILD ), - GUI_SPATIAL_IO_PORT(ContainerSpatialIOPort.class, TileSpatialIOPort.class, WORLD, SecurityPermissions.BUILD), + GUI_SPATIAL_IO_PORT( ContainerSpatialIOPort.class, TileSpatialIOPort.class, WORLD, SecurityPermissions.BUILD ), - GUI_INSCRIBER(ContainerInscriber.class, TileInscriber.class, WORLD, null), + GUI_INSCRIBER( ContainerInscriber.class, TileInscriber.class, WORLD, null ), - GUI_CELL_WORKBENCH(ContainerCellWorkbench.class, TileCellWorkbench.class, WORLD, null), + GUI_CELL_WORKBENCH( ContainerCellWorkbench.class, TileCellWorkbench.class, WORLD, null ), - GUI_MAC(ContainerMAC.class, TileMolecularAssembler.class, WORLD, null), + GUI_MAC( ContainerMAC.class, TileMolecularAssembler.class, WORLD, null ), - GUI_CRAFTING_AMOUNT(ContainerCraftAmount.class, ITerminalHost.class, ITEM_OR_WORLD, SecurityPermissions.CRAFT), + GUI_CRAFTING_AMOUNT( ContainerCraftAmount.class, ITerminalHost.class, ITEM_OR_WORLD, SecurityPermissions.CRAFT ), - GUI_CRAFTING_CONFIRM(ContainerCraftConfirm.class, ITerminalHost.class, ITEM_OR_WORLD, SecurityPermissions.CRAFT), + GUI_CRAFTING_CONFIRM( ContainerCraftConfirm.class, ITerminalHost.class, ITEM_OR_WORLD, SecurityPermissions.CRAFT ), - GUI_INTERFACE_TERMINAL(ContainerInterfaceTerminal.class, PartMonitor.class, WORLD, SecurityPermissions.BUILD), + GUI_INTERFACE_TERMINAL( ContainerInterfaceTerminal.class, PartMonitor.class, WORLD, SecurityPermissions.BUILD ), - GUI_CRAFTING_STATUS(ContainerCraftingStatus.class, ITerminalHost.class, ITEM_OR_WORLD, SecurityPermissions.CRAFT); + GUI_CRAFTING_STATUS( ContainerCraftingStatus.class, ITerminalHost.class, ITEM_OR_WORLD, SecurityPermissions.CRAFT ); private final Class Tile; - private Class Gui; private final Class Container; + private Class Gui; private GuiHostType type; private SecurityPermissions requiredPermission; - GuiBridge() { + GuiBridge() + { this.Tile = null; this.Gui = null; this.Container = null; } + GuiBridge( Class _Container, SecurityPermissions requiredPermission ) + { + this.requiredPermission = requiredPermission; + this.Container = _Container; + this.Tile = null; + this.getGui(); + } + /** * I honestly wish I could just use the GuiClass Names myself, but I can't access them without MC's Server * Exploding. */ private void getGui() { - if ( Platform.isClient() ) + if( Platform.isClient() ) { final String start = this.Container.getName(); String guiClass = start.replaceFirst( "container.", "client.gui." ).replace( ".Container", ".Gui" ); - if ( start.equals( guiClass ) ) + if( start.equals( guiClass ) ) throw new RuntimeException( "Unable to find gui class" ); this.Gui = ReflectionHelper.getClass( this.getClass().getClassLoader(), guiClass ); - if ( this.Gui == null ) + if( this.Gui == null ) throw new RuntimeException( "Cannot Load class: " + guiClass ); } } - GuiBridge( Class _Container, SecurityPermissions requiredPermission ) { - this.requiredPermission = requiredPermission; - this.Container = _Container; - this.Tile = null; - this.getGui(); - } - - GuiBridge( Class _Container, Class _Tile, GuiHostType type, SecurityPermissions requiredPermission ) { + GuiBridge( Class _Container, Class _Tile, GuiHostType type, SecurityPermissions requiredPermission ) + { this.requiredPermission = requiredPermission; this.Container = _Container; this.type = type; @@ -240,125 +244,69 @@ public enum GuiBridge implements IGuiHandler this.getGui(); } - public boolean CorrectTileOrPart(Object tE) + @Override + public Object getServerGuiElement( int ID_ORDINAL, EntityPlayer player, World w, int x, int y, int z ) { - if ( this.Tile == null ) + ForgeDirection side = ForgeDirection.getOrientation( ID_ORDINAL & 0x07 ); + GuiBridge ID = values()[ID_ORDINAL >> 4]; + boolean stem = ( ( ID_ORDINAL >> 3 ) & 1 ) == 1; + + if( ID.type.isItem() && stem ) + { + ItemStack it = player.inventory.getCurrentItem(); + Object myItem = this.getGuiObject( it, player, w, x, y, z ); + if( myItem != null && ID.CorrectTileOrPart( myItem ) ) + return this.updateGui( ID.ConstructContainer( player.inventory, side, myItem ), w, x, y, z, side, myItem ); + } + + if( ID.type.isTile() ) + { + TileEntity TE = w.getTileEntity( x, y, z ); + if( TE instanceof IPartHost ) + { + ( (IPartHost) TE ).getPart( side ); + IPart part = ( (IPartHost) TE ).getPart( side ); + if( ID.CorrectTileOrPart( part ) ) + return this.updateGui( ID.ConstructContainer( player.inventory, side, part ), w, x, y, z, side, part ); + } + else + { + if( ID.CorrectTileOrPart( TE ) ) + return this.updateGui( ID.ConstructContainer( player.inventory, side, TE ), w, x, y, z, side, TE ); + } + } + + return new ContainerNull(); + } + + private Object getGuiObject( ItemStack it, EntityPlayer player, World w, int x, int y, int z ) + { + if( it != null ) + { + if( it.getItem() instanceof IGuiItem ) + { + return ( (IGuiItem) it.getItem() ).getGuiObject( it, w, x, y, z ); + } + + IWirelessTermHandler wh = AEApi.instance().registries().wireless().getWirelessTerminalHandler( it ); + if( wh != null ) + return new WirelessTerminalGuiObject( wh, it, player, w, x, y, z ); + } + + return null; + } + + public boolean CorrectTileOrPart( Object tE ) + { + if( this.Tile == null ) throw new RuntimeException( "This Gui Cannot use the standard Handler." ); return this.Tile.isInstance( tE ); } - public Object ConstructContainer(InventoryPlayer inventory, ForgeDirection side, Object tE) + private Object updateGui( Object newContainer, World w, int x, int y, int z, ForgeDirection side, Object myItem ) { - try - { - Constructor[] c = this.Container.getConstructors(); - if ( c.length == 0 ) - throw new AppEngException( "Invalid Gui Class" ); - - Constructor target = this.findConstructor( c, inventory, tE ); - - if ( target == null ) - { - throw new RuntimeException( "Cannot find " + this.Container.getName() + "( " + this.typeName( inventory ) + ", " + this.typeName( tE ) + " )" ); - } - - Object o = target.newInstance( inventory, tE ); - - /** - * triggers achievement when the player sees presses. - */ - if ( o instanceof AEBaseContainer ) - { - AEBaseContainer bc = (AEBaseContainer) o; - for (Object so : bc.inventorySlots) - { - if ( so instanceof Slot ) - { - ItemStack is = ((Slot) so).getStack(); - - final IMaterials materials = AEApi.instance().definitions().materials(); - this.addPressAchievementToPlayer( is, materials, inventory.player ); - } - } - } - - return o; - } - catch (Throwable t) - { - throw new RuntimeException( t ); - } - } - - private void addPressAchievementToPlayer( ItemStack newItem, IMaterials possibleMaterials, EntityPlayer player ) - { - final IComparableDefinition logic = possibleMaterials.logicProcessorPress(); - final IComparableDefinition eng = possibleMaterials.engProcessorPress(); - final IComparableDefinition calc = possibleMaterials.calcProcessorPress(); - final IComparableDefinition silicon = possibleMaterials.siliconPress(); - - final List presses = Lists.newArrayList( logic, eng, calc, silicon ); - - for ( IComparableDefinition press : presses ) - { - if ( press.isSameAs( newItem ) ) - { - Achievements.Presses.addToPlayer( player ); - - return; - } - } - } - - public Object ConstructGui(InventoryPlayer inventory, ForgeDirection side, Object tE) - { - try - { - Constructor[] c = this.Gui.getConstructors(); - if ( c.length == 0 ) - throw new AppEngException( "Invalid Gui Class" ); - - Constructor target = this.findConstructor( c, inventory, tE ); - - if ( target == null ) - { - throw new RuntimeException( "Cannot find " + this.Container.getName() + "( " + this.typeName( inventory ) + ", " + this.typeName( tE ) + " )" ); - } - - return target.newInstance( inventory, tE ); - } - catch (Throwable t) - { - throw new RuntimeException( t ); - } - } - - private String typeName(Object inventory) - { - if ( inventory == null ) - return "NULL"; - - return inventory.getClass().getName(); - } - - private Constructor findConstructor(Constructor[] c, InventoryPlayer inventory, Object tE) - { - for (Constructor con : c) - { - Class[] types = con.getParameterTypes(); - if ( types.length == 2 ) - { - if ( types[0].isAssignableFrom( inventory.getClass() ) && types[1].isAssignableFrom( tE.getClass() ) ) - return con; - } - } - return null; - } - - private Object updateGui(Object newContainer, World w, int x, int y, int z, ForgeDirection side, Object myItem) - { - if ( newContainer instanceof AEBaseContainer ) + if( newContainer instanceof AEBaseContainer ) { AEBaseContainer bc = (AEBaseContainer) newContainer; bc.openContext = new ContainerOpenContext( myItem ); @@ -372,87 +320,120 @@ public enum GuiBridge implements IGuiHandler return newContainer; } - @Override - public Object getServerGuiElement(int ID_ORDINAL, EntityPlayer player, World w, int x, int y, int z) + public Object ConstructContainer( InventoryPlayer inventory, ForgeDirection side, Object tE ) { - ForgeDirection side = ForgeDirection.getOrientation( ID_ORDINAL & 0x07 ); - GuiBridge ID = values()[ID_ORDINAL >> 4]; - boolean stem = ((ID_ORDINAL >> 3) & 1) == 1; - - if ( ID.type.isItem() && stem ) + try { - ItemStack it = player.inventory.getCurrentItem(); - Object myItem = this.getGuiObject( it, player, w, x, y, z ); - if ( myItem != null && ID.CorrectTileOrPart( myItem ) ) - return this.updateGui( ID.ConstructContainer( player.inventory, side, myItem ), w, x, y, z, side, myItem ); - } + Constructor[] c = this.Container.getConstructors(); + if( c.length == 0 ) + throw new AppEngException( "Invalid Gui Class" ); - if ( ID.type.isTile() ) + Constructor target = this.findConstructor( c, inventory, tE ); + + if( target == null ) + { + throw new RuntimeException( "Cannot find " + this.Container.getName() + "( " + this.typeName( inventory ) + ", " + this.typeName( tE ) + " )" ); + } + + Object o = target.newInstance( inventory, tE ); + + /** + * triggers achievement when the player sees presses. + */ + if( o instanceof AEBaseContainer ) + { + AEBaseContainer bc = (AEBaseContainer) o; + for( Object so : bc.inventorySlots ) + { + if( so instanceof Slot ) + { + ItemStack is = ( (Slot) so ).getStack(); + + final IMaterials materials = AEApi.instance().definitions().materials(); + this.addPressAchievementToPlayer( is, materials, inventory.player ); + } + } + } + + return o; + } + catch( Throwable t ) { - TileEntity TE = w.getTileEntity( x, y, z ); - if ( TE instanceof IPartHost ) - { - ((IPartHost) TE).getPart( side ); - IPart part = ((IPartHost) TE).getPart( side ); - if ( ID.CorrectTileOrPart( part ) ) - return this.updateGui( ID.ConstructContainer( player.inventory, side, part ), w, x, y, z, side, part ); - } - else - { - if ( ID.CorrectTileOrPart( TE ) ) - return this.updateGui( ID.ConstructContainer( player.inventory, side, TE ), w, x, y, z, side, TE ); - } + throw new RuntimeException( t ); } - - return new ContainerNull(); } - private Object getGuiObject(ItemStack it, EntityPlayer player, World w, int x, int y, int z) + private Constructor findConstructor( Constructor[] c, InventoryPlayer inventory, Object tE ) { - if ( it != null ) + for( Constructor con : c ) { - if ( it.getItem() instanceof IGuiItem ) + Class[] types = con.getParameterTypes(); + if( types.length == 2 ) { - return ((IGuiItem) it.getItem()).getGuiObject( it, w, x, y, z ); + if( types[0].isAssignableFrom( inventory.getClass() ) && types[1].isAssignableFrom( tE.getClass() ) ) + return con; } - - IWirelessTermHandler wh = AEApi.instance().registries().wireless().getWirelessTerminalHandler( it ); - if ( wh != null ) - return new WirelessTerminalGuiObject( wh, it, player, w, x, y, z ); } - return null; } + private String typeName( Object inventory ) + { + if( inventory == null ) + return "NULL"; + + return inventory.getClass().getName(); + } + + private void addPressAchievementToPlayer( ItemStack newItem, IMaterials possibleMaterials, EntityPlayer player ) + { + final IComparableDefinition logic = possibleMaterials.logicProcessorPress(); + final IComparableDefinition eng = possibleMaterials.engProcessorPress(); + final IComparableDefinition calc = possibleMaterials.calcProcessorPress(); + final IComparableDefinition silicon = possibleMaterials.siliconPress(); + + final List presses = Lists.newArrayList( logic, eng, calc, silicon ); + + for( IComparableDefinition press : presses ) + { + if( press.isSameAs( newItem ) ) + { + Achievements.Presses.addToPlayer( player ); + + return; + } + } + } + @Override - public Object getClientGuiElement(int ID_ORDINAL, EntityPlayer player, World w, int x, int y, int z) + public Object getClientGuiElement( int ID_ORDINAL, EntityPlayer player, World w, int x, int y, int z ) { ForgeDirection side = ForgeDirection.getOrientation( ID_ORDINAL & 0x07 ); GuiBridge ID = values()[ID_ORDINAL >> 4]; - boolean stem = ((ID_ORDINAL >> 3) & 1) == 1; + boolean stem = ( ( ID_ORDINAL >> 3 ) & 1 ) == 1; - if ( ID.type.isItem() && stem ) + if( ID.type.isItem() && stem ) { ItemStack it = player.inventory.getCurrentItem(); Object myItem = this.getGuiObject( it, player, w, x, y, z ); - if ( ID.CorrectTileOrPart( myItem ) ) + if( ID.CorrectTileOrPart( myItem ) ) return ID.ConstructGui( player.inventory, side, myItem ); } - if ( ID.type.isTile() ) + if( ID.type.isTile() ) { TileEntity TE = w.getTileEntity( x, y, z ); - if ( TE instanceof IPartHost ) + if( TE instanceof IPartHost ) { - ((IPartHost) TE).getPart( side ); - IPart part = ((IPartHost) TE).getPart( side ); - if ( ID.CorrectTileOrPart( part ) ) + ( (IPartHost) TE ).getPart( side ); + IPart part = ( (IPartHost) TE ).getPart( side ); + if( ID.CorrectTileOrPart( part ) ) return ID.ConstructGui( player.inventory, side, part ); } else { - if ( ID.CorrectTileOrPart( TE ) ) + if( ID.CorrectTileOrPart( TE ) ) return ID.ConstructGui( player.inventory, side, TE ); } } @@ -460,38 +441,61 @@ public enum GuiBridge implements IGuiHandler return new GuiNull( new ContainerNull() ); } - public boolean hasPermissions(TileEntity te, int x, int y, int z, ForgeDirection side, EntityPlayer player) + public Object ConstructGui( InventoryPlayer inventory, ForgeDirection side, Object tE ) + { + try + { + Constructor[] c = this.Gui.getConstructors(); + if( c.length == 0 ) + throw new AppEngException( "Invalid Gui Class" ); + + Constructor target = this.findConstructor( c, inventory, tE ); + + if( target == null ) + { + throw new RuntimeException( "Cannot find " + this.Container.getName() + "( " + this.typeName( inventory ) + ", " + this.typeName( tE ) + " )" ); + } + + return target.newInstance( inventory, tE ); + } + catch( Throwable t ) + { + throw new RuntimeException( t ); + } + } + + public boolean hasPermissions( TileEntity te, int x, int y, int z, ForgeDirection side, EntityPlayer player ) { World w = player.getEntityWorld(); - if ( Platform.hasPermissions( te != null ? new DimensionalCoord( te ) : new DimensionalCoord( player.worldObj, x, y, z ), player ) ) + if( Platform.hasPermissions( te != null ? new DimensionalCoord( te ) : new DimensionalCoord( player.worldObj, x, y, z ), player ) ) { - if ( this.type.isItem() ) + if( this.type.isItem() ) { ItemStack it = player.inventory.getCurrentItem(); - if ( it != null && it.getItem() instanceof IGuiItem ) + if( it != null && it.getItem() instanceof IGuiItem ) { - Object myItem = ((IGuiItem) it.getItem()).getGuiObject( it, w, x, y, z ); - if ( this.CorrectTileOrPart( myItem ) ) + Object myItem = ( (IGuiItem) it.getItem() ).getGuiObject( it, w, x, y, z ); + if( this.CorrectTileOrPart( myItem ) ) { return true; } } } - if ( this.type.isTile() ) + if( this.type.isTile() ) { TileEntity TE = w.getTileEntity( x, y, z ); - if ( TE instanceof IPartHost ) + if( TE instanceof IPartHost ) { - ((IPartHost) TE).getPart( side ); - IPart part = ((IPartHost) TE).getPart( side ); - if ( this.CorrectTileOrPart( part ) ) + ( (IPartHost) TE ).getPart( side ); + IPart part = ( (IPartHost) TE ).getPart( side ); + if( this.CorrectTileOrPart( part ) ) return this.securityCheck( part, player ); } else { - if ( this.CorrectTileOrPart( TE ) ) + if( this.CorrectTileOrPart( TE ) ) return this.securityCheck( TE, player ); } } @@ -499,29 +503,29 @@ public enum GuiBridge implements IGuiHandler return false; } - private boolean securityCheck(Object te, EntityPlayer player) + private boolean securityCheck( Object te, EntityPlayer player ) { - if ( te instanceof IActionHost && this.requiredPermission != null ) + if( te instanceof IActionHost && this.requiredPermission != null ) { boolean requirePower = false; - IGridNode gn = ((IActionHost) te).getActionableNode(); - if ( gn != null ) + IGridNode gn = ( (IActionHost) te ).getActionableNode(); + if( gn != null ) { IGrid g = gn.getGrid(); - if ( g != null ) + if( g != null ) { - if ( requirePower ) + if( requirePower ) { IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if ( !eg.isNetworkPowered() ) + if( !eg.isNetworkPowered() ) { return false; } } ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if ( sg.hasPermission( player, this.requiredPermission ) ) + if( sg.hasPermission( player, this.requiredPermission ) ) return true; } } diff --git a/src/main/java/appeng/core/sync/GuiHostType.java b/src/main/java/appeng/core/sync/GuiHostType.java index 572465892..6127a585c 100644 --- a/src/main/java/appeng/core/sync/GuiHostType.java +++ b/src/main/java/appeng/core/sync/GuiHostType.java @@ -18,6 +18,7 @@ package appeng.core.sync; + public enum GuiHostType { ITEM_OR_WORLD, ITEM, WORLD; diff --git a/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java b/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java index 0ae96e3d7..261d31089 100644 --- a/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java @@ -18,6 +18,7 @@ package appeng.core.sync.network; + import java.lang.reflect.InvocationTargetException; import io.netty.buffer.ByteBuf; @@ -31,11 +32,12 @@ import appeng.core.AELog; import appeng.core.sync.AppEngPacket; import appeng.core.sync.AppEngPacketHandlerBase; + public class AppEngClientPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler { @Override - public void onPacketData(INetworkInfo network, FMLProxyPacket packet, EntityPlayer player) + public void onPacketData( INetworkInfo network, FMLProxyPacket packet, EntityPlayer player ) { ByteBuf stream = packet.payload(); int packetType = -1; @@ -48,22 +50,21 @@ public class AppEngClientPacketHandler extends AppEngPacketHandlerBase implement AppEngPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); pack.clientPacketData( network, pack, player ); } - catch (InstantiationException e) + catch( InstantiationException e ) { AELog.error( e ); } - catch (IllegalAccessException e) + catch( IllegalAccessException e ) { AELog.error( e ); } - catch (IllegalArgumentException e) + catch( IllegalArgumentException e ) { AELog.error( e ); } - catch (InvocationTargetException e) + catch( InvocationTargetException e ) { AELog.error( e ); } - } } diff --git a/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java b/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java index cf5780518..2a9a51dc0 100644 --- a/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java @@ -18,6 +18,7 @@ package appeng.core.sync.network; + import java.lang.reflect.InvocationTargetException; import io.netty.buffer.ByteBuf; @@ -30,11 +31,12 @@ import appeng.core.AELog; import appeng.core.sync.AppEngPacket; import appeng.core.sync.AppEngPacketHandlerBase; + public final class AppEngServerPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler { @Override - public void onPacketData(INetworkInfo manager, FMLProxyPacket packet, EntityPlayer player) + public void onPacketData( INetworkInfo manager, FMLProxyPacket packet, EntityPlayer player ) { ByteBuf stream = packet.payload(); int packetType = -1; @@ -45,22 +47,21 @@ public final class AppEngServerPacketHandler extends AppEngPacketHandlerBase imp AppEngPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); pack.serverPacketData( manager, pack, player ); } - catch (InstantiationException e) + catch( InstantiationException e ) { AELog.error( e ); } - catch (IllegalAccessException e) + catch( IllegalAccessException e ) { AELog.error( e ); } - catch (IllegalArgumentException e) + catch( IllegalArgumentException e ) { AELog.error( e ); } - catch (InvocationTargetException e) + catch( InvocationTargetException e ) { AELog.error( e ); } - } } diff --git a/src/main/java/appeng/core/sync/network/IPacketHandler.java b/src/main/java/appeng/core/sync/network/IPacketHandler.java index 466a4600a..44a42fc79 100644 --- a/src/main/java/appeng/core/sync/network/IPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/IPacketHandler.java @@ -18,13 +18,14 @@ package appeng.core.sync.network; + import net.minecraft.entity.player.EntityPlayer; import cpw.mods.fml.common.network.internal.FMLProxyPacket; + public interface IPacketHandler { - void onPacketData(INetworkInfo manager, FMLProxyPacket packet, EntityPlayer player); - + void onPacketData( INetworkInfo manager, FMLProxyPacket packet, EntityPlayer player ); } diff --git a/src/main/java/appeng/core/sync/network/NetworkHandler.java b/src/main/java/appeng/core/sync/network/NetworkHandler.java index ae4d73d0b..e540294a9 100644 --- a/src/main/java/appeng/core/sync/network/NetworkHandler.java +++ b/src/main/java/appeng/core/sync/network/NetworkHandler.java @@ -34,6 +34,7 @@ import cpw.mods.fml.common.network.NetworkRegistry; import appeng.core.WorldSettings; import appeng.core.sync.AppEngPacket; + public class NetworkHandler { @@ -45,7 +46,8 @@ public class NetworkHandler final IPacketHandler clientHandler; final IPacketHandler serveHandler; - public NetworkHandler(String channelName) { + public NetworkHandler( String channelName ) + { FMLCommonHandler.instance().bus().register( this ); this.ec = NetworkRegistry.INSTANCE.newEventDrivenChannel( this.myChannelName = channelName ); this.ec.register( this ); @@ -54,55 +56,55 @@ public class NetworkHandler this.serveHandler = this.createServerSide(); } - private IPacketHandler createServerSide() - { - try - { - return new AppEngServerPacketHandler(); - } - catch (Throwable t) - { - return null; - } - } - private IPacketHandler createClientSide() { try { return new AppEngClientPacketHandler(); } - catch (Throwable t) + catch( Throwable t ) + { + return null; + } + } + + private IPacketHandler createServerSide() + { + try + { + return new AppEngServerPacketHandler(); + } + catch( Throwable t ) { return null; } } @SubscribeEvent - public void newConnection(ServerConnectionFromClientEvent ev) + public void newConnection( ServerConnectionFromClientEvent ev ) { WorldSettings.getInstance().sendToPlayer( ev.manager ); } @SubscribeEvent - public void newConnection(PlayerLoggedInEvent loginEvent) + public void newConnection( PlayerLoggedInEvent loginEvent ) { - if ( loginEvent.player instanceof EntityPlayerMP ) + if( loginEvent.player instanceof EntityPlayerMP ) WorldSettings.getInstance().sendToPlayer( null ); } @SubscribeEvent - public void serverPacket(ServerCustomPacketEvent ev) + public void serverPacket( ServerCustomPacketEvent ev ) { NetHandlerPlayServer srv = (NetHandlerPlayServer) ev.packet.handler(); - if ( this.serveHandler != null ) + if( this.serveHandler != null ) this.serveHandler.onPacketData( null, ev.packet, srv.playerEntity ); } @SubscribeEvent - public void clientPacket(ClientCustomPacketEvent ev) + public void clientPacket( ClientCustomPacketEvent ev ) { - if ( this.clientHandler != null ) + if( this.clientHandler != null ) this.clientHandler.onPacketData( null, ev.packet, null ); } @@ -111,29 +113,28 @@ public class NetworkHandler return this.myChannelName; } - public void sendToAll(AppEngPacket message) + public void sendToAll( AppEngPacket message ) { this.ec.sendToAll( message.getProxy() ); } - public void sendTo(AppEngPacket message, EntityPlayerMP player) + public void sendTo( AppEngPacket message, EntityPlayerMP player ) { this.ec.sendTo( message.getProxy(), player ); } - public void sendToAllAround(AppEngPacket message, NetworkRegistry.TargetPoint point) + public void sendToAllAround( AppEngPacket message, NetworkRegistry.TargetPoint point ) { this.ec.sendToAllAround( message.getProxy(), point ); } - public void sendToDimension(AppEngPacket message, int dimensionId) + public void sendToDimension( AppEngPacket message, int dimensionId ) { this.ec.sendToDimension( message.getProxy(), dimensionId ); } - public void sendToServer(AppEngPacket message) + public void sendToServer( AppEngPacket message ) { this.ec.sendToServer( message.getProxy() ); } - } diff --git a/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java b/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java index 6e6127ae8..52584982e 100644 --- a/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java +++ b/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import java.io.IOException; import io.netty.buffer.ByteBuf; @@ -35,6 +36,7 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.item.AEItemStack; + public class PacketAssemblerAnimation extends AppEngPacket { @@ -45,7 +47,8 @@ public class PacketAssemblerAnimation extends AppEngPacket final public IAEItemStack is; // automatic. - public PacketAssemblerAnimation(ByteBuf stream) throws IOException { + public PacketAssemblerAnimation( ByteBuf stream ) throws IOException + { this.x = stream.readInt(); this.y = stream.readInt(); this.z = stream.readInt(); @@ -53,19 +56,9 @@ public class PacketAssemblerAnimation extends AppEngPacket this.is = AEItemStack.loadItemStackFromPacket( stream ); } - @Override - @SideOnly(Side.CLIENT) - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - double d0 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - double d1 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - double d2 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - - CommonHelper.proxy.spawnEffect( EffectType.Assembler, player.getEntityWorld(), this.x + d0, this.y + d1, this.z + d2, this ); - } - // api - public PacketAssemblerAnimation(int x, int y, int z, byte rate, IAEItemStack is) throws IOException { + public PacketAssemblerAnimation( int x, int y, int z, byte rate, IAEItemStack is ) throws IOException + { ByteBuf data = Unpooled.buffer(); @@ -79,4 +72,15 @@ public class PacketAssemblerAnimation extends AppEngPacket this.configureWrite( data ); } + + @Override + @SideOnly( Side.CLIENT ) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + double d0 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + double d1 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + double d2 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + + CommonHelper.proxy.spawnEffect( EffectType.Assembler, player.getEntityWorld(), this.x + d0, this.y + d1, this.z + d2, this ); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketClick.java b/src/main/java/appeng/core/sync/packets/PacketClick.java index f3abfbc1a..457454f36 100644 --- a/src/main/java/appeng/core/sync/packets/PacketClick.java +++ b/src/main/java/appeng/core/sync/packets/PacketClick.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -34,6 +35,7 @@ import appeng.core.sync.network.INetworkInfo; import appeng.items.tools.ToolNetworkTool; import appeng.items.tools.powered.ToolColorApplicator; + public class PacketClick extends AppEngPacket { @@ -46,7 +48,8 @@ public class PacketClick extends AppEngPacket final float hitZ; // automatic. - public PacketClick(ByteBuf stream) { + public PacketClick( ByteBuf stream ) + { this.x = stream.readInt(); this.y = stream.readInt(); this.z = stream.readInt(); @@ -56,39 +59,9 @@ public class PacketClick extends AppEngPacket this.hitZ = stream.readFloat(); } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - ItemStack is = player.inventory.getCurrentItem(); - final IItems items = AEApi.instance().definitions().items(); - final IComparableDefinition maybeMemoryCard = items.memoryCard(); - final IComparableDefinition maybeColorApplicator = items.colorApplicator(); - - if ( is != null ) - { - if ( is.getItem() instanceof ToolNetworkTool ) - { - ToolNetworkTool tnt = (ToolNetworkTool) is.getItem(); - tnt.serverSideToolLogic( is, player, player.worldObj, this.x, this.y, this.z, this.side, this.hitX, this.hitY, this.hitZ ); - } - - else if ( maybeMemoryCard.isSameAs( is ) ) - { - IMemoryCard mem = (IMemoryCard) is.getItem(); - mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - is.setTagCompound( null ); - } - - else if ( maybeColorApplicator.isSameAs( is ) ) - { - ToolColorApplicator mem = (ToolColorApplicator) is.getItem(); - mem.cycleColors( is, mem.getColor( is ), 1 ); - } - } - } - // api - public PacketClick(int x, int y, int z, int side, float hitX, float hitY, float hitZ) { + public PacketClick( int x, int y, int z, int side, float hitX, float hitY, float hitZ ) + { ByteBuf data = Unpooled.buffer(); @@ -103,4 +76,35 @@ public class PacketClick extends AppEngPacket this.configureWrite( data ); } + + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + ItemStack is = player.inventory.getCurrentItem(); + final IItems items = AEApi.instance().definitions().items(); + final IComparableDefinition maybeMemoryCard = items.memoryCard(); + final IComparableDefinition maybeColorApplicator = items.colorApplicator(); + + if( is != null ) + { + if( is.getItem() instanceof ToolNetworkTool ) + { + ToolNetworkTool tnt = (ToolNetworkTool) is.getItem(); + tnt.serverSideToolLogic( is, player, player.worldObj, this.x, this.y, this.z, this.side, this.hitX, this.hitY, this.hitZ ); + } + + else if( maybeMemoryCard.isSameAs( is ) ) + { + IMemoryCard mem = (IMemoryCard) is.getItem(); + mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); + is.setTagCompound( null ); + } + + else if( maybeColorApplicator.isSameAs( is ) ) + { + ToolColorApplicator mem = (ToolColorApplicator) is.getItem(); + mem.cycleColors( is, mem.getColor( is ), 1 ); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java b/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java index 75ca6987b..70ebb478c 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -31,6 +32,7 @@ import appeng.core.sync.network.INetworkInfo; import appeng.core.sync.network.NetworkHandler; import appeng.services.compass.ICompassCallback; + public class PacketCompassRequest extends AppEngPacket implements ICompassCallback { @@ -42,30 +44,17 @@ public class PacketCompassRequest extends AppEngPacket implements ICompassCallba EntityPlayer talkBackTo; // automatic. - public PacketCompassRequest(ByteBuf stream) { + public PacketCompassRequest( ByteBuf stream ) + { this.attunement = stream.readLong(); this.cx = stream.readInt(); this.cz = stream.readInt(); this.cdy = stream.readInt(); } - @Override - public void calculatedDirection(boolean hasResult, boolean spin, double radians, double dist) - { - NetworkHandler.instance.sendTo( new PacketCompassResponse( this, hasResult, spin, radians ), (EntityPlayerMP) this.talkBackTo ); - } - - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - this.talkBackTo = player; - - DimensionalCoord loc = new DimensionalCoord( player.worldObj, this.cx << 4, this.cdy << 5, this.cz << 4 ); - WorldSettings.getInstance().getCompass().getCompassDirection( loc, 174, this ); - } - // api - public PacketCompassRequest(long attunement, int cx, int cz, int cdy) { + public PacketCompassRequest( long attunement, int cx, int cz, int cdy ) + { ByteBuf data = Unpooled.buffer(); @@ -76,6 +65,20 @@ public class PacketCompassRequest extends AppEngPacket implements ICompassCallba data.writeInt( this.cdy = cdy ); this.configureWrite( data ); + } + @Override + public void calculatedDirection( boolean hasResult, boolean spin, double radians, double dist ) + { + NetworkHandler.instance.sendTo( new PacketCompassResponse( this, hasResult, spin, radians ), (EntityPlayerMP) this.talkBackTo ); + } + + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + this.talkBackTo = player; + + DimensionalCoord loc = new DimensionalCoord( player.worldObj, this.cx << 4, this.cdy << 5, this.cz << 4 ); + WorldSettings.getInstance().getCompass().getCompassDirection( loc, 174, this ); } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java b/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java index 1c9700a4c..5d85981d8 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -28,6 +29,7 @@ import appeng.core.sync.network.INetworkInfo; import appeng.hooks.CompassManager; import appeng.hooks.CompassResult; + public class PacketCompassResponse extends AppEngPacket { @@ -39,7 +41,8 @@ public class PacketCompassResponse extends AppEngPacket public CompassResult cr; // automatic. - public PacketCompassResponse(ByteBuf stream) { + public PacketCompassResponse( ByteBuf stream ) + { this.attunement = stream.readLong(); this.cx = stream.readInt(); this.cz = stream.readInt(); @@ -48,14 +51,9 @@ public class PacketCompassResponse extends AppEngPacket this.cr = new CompassResult( stream.readBoolean(), stream.readBoolean(), stream.readDouble() ); } - @Override - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - CompassManager.INSTANCE.postResult( this.attunement, this.cx << 4, this.cdy << 5, this.cz << 4, this.cr ); - } - // api - public PacketCompassResponse(PacketCompassRequest req, boolean hasResult, boolean spin, double radians) { + public PacketCompassResponse( PacketCompassRequest req, boolean hasResult, boolean spin, double radians ) + { ByteBuf data = Unpooled.buffer(); @@ -70,6 +68,11 @@ public class PacketCompassResponse extends AppEngPacket data.writeDouble( radians ); this.configureWrite( data ); + } + @Override + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + CompassManager.INSTANCE.postResult( this.attunement, this.cx << 4, this.cdy << 5, this.cz << 4, this.cr ); } } \ No newline at end of file diff --git a/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java b/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java index 345ec0009..f5985fefd 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; @@ -42,36 +43,35 @@ import appeng.client.gui.implementations.GuiInterfaceTerminal; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; + public class PacketCompressedNBT extends AppEngPacket { + // input. + final NBTTagCompound in; // output... final private ByteBuf data; final private GZIPOutputStream compressFrame; - int writtenBytes = 0; - boolean empty = true; - // input. - final NBTTagCompound in; - // automatic. - public PacketCompressedNBT(final ByteBuf stream) throws IOException { + public PacketCompressedNBT( final ByteBuf stream ) throws IOException + { this.data = null; this.compressFrame = null; - GZIPInputStream gzReader = new GZIPInputStream( new InputStream() { + GZIPInputStream gzReader = new GZIPInputStream( new InputStream() + { @Override public int read() throws IOException { - if ( stream.readableBytes() <= 0 ) + if( stream.readableBytes() <= 0 ) return -1; return stream.readByte() & 0xff; } - } ); DataInputStream inStream = new DataInputStream( gzReader ); @@ -79,33 +79,23 @@ public class PacketCompressedNBT extends AppEngPacket inStream.close(); } - @Override - @SideOnly(Side.CLIENT) - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - GuiScreen gs = Minecraft.getMinecraft().currentScreen; - - if ( gs instanceof GuiInterfaceTerminal ) - ((GuiInterfaceTerminal) gs).postUpdate( this.in ); - - } - // api - public PacketCompressedNBT(NBTTagCompound din) throws IOException { + public PacketCompressedNBT( NBTTagCompound din ) throws IOException + { this.data = Unpooled.buffer( 2048 ); this.data.writeInt( this.getPacketID() ); this.in = din; - this.compressFrame = new GZIPOutputStream( new OutputStream() { + this.compressFrame = new GZIPOutputStream( new OutputStream() + { @Override - public void write(int value) throws IOException + public void write( int value ) throws IOException { PacketCompressedNBT.this.data.writeByte( value ); } - } ); CompressedStreamTools.write( din, new DataOutputStream( this.compressFrame ) ); @@ -114,4 +104,13 @@ public class PacketCompressedNBT extends AppEngPacket this.configureWrite( this.data ); } + @Override + @SideOnly( Side.CLIENT ) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + GuiScreen gs = Minecraft.getMinecraft().currentScreen; + + if( gs instanceof GuiInterfaceTerminal ) + ( (GuiInterfaceTerminal) gs ).postUpdate( this.in ); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketConfigButton.java b/src/main/java/appeng/core/sync/packets/PacketConfigButton.java index 4e271db41..056b3528f 100644 --- a/src/main/java/appeng/core/sync/packets/PacketConfigButton.java +++ b/src/main/java/appeng/core/sync/packets/PacketConfigButton.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -32,6 +33,7 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.Platform; + public class PacketConfigButton extends AppEngPacket { @@ -39,26 +41,15 @@ public class PacketConfigButton extends AppEngPacket final public boolean rotationDirection; // automatic. - public PacketConfigButton(ByteBuf stream) { + public PacketConfigButton( ByteBuf stream ) + { this.option = Settings.values()[stream.readInt()]; this.rotationDirection = stream.readBoolean(); } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - EntityPlayerMP sender = (EntityPlayerMP) player; - AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; - if ( baseContainer.getTarget() instanceof IConfigurableObject ) - { - IConfigManager cm = ((IConfigurableObject) baseContainer.getTarget()).getConfigManager(); - Enum newState = Platform.rotateEnum( cm.getSetting( this.option ), this.rotationDirection, this.option.getPossibleValues() ); - cm.putSetting( this.option, newState ); - } - } - // api - public PacketConfigButton(Settings option, boolean rotationDirection) { + public PacketConfigButton( Settings option, boolean rotationDirection ) + { this.option = option; this.rotationDirection = rotationDirection; @@ -70,4 +61,17 @@ public class PacketConfigButton extends AppEngPacket this.configureWrite( data ); } + + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + EntityPlayerMP sender = (EntityPlayerMP) player; + AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; + if( baseContainer.getTarget() instanceof IConfigurableObject ) + { + IConfigManager cm = ( (IConfigurableObject) baseContainer.getTarget() ).getConfigManager(); + Enum newState = Platform.rotateEnum( cm.getSetting( this.option ), this.rotationDirection, this.option.getPossibleValues() ); + cm.putSetting( this.option, newState ); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java b/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java index 9d9b10b56..cdb258fb0 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java +++ b/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import java.util.concurrent.Future; import io.netty.buffer.ByteBuf; @@ -41,6 +42,7 @@ import appeng.core.sync.GuiBridge; import appeng.core.sync.network.INetworkInfo; import appeng.util.Platform; + public class PacketCraftRequest extends AppEngPacket { @@ -48,66 +50,13 @@ public class PacketCraftRequest extends AppEngPacket final public boolean heldShift; // automatic. - public PacketCraftRequest(ByteBuf stream) + public PacketCraftRequest( ByteBuf stream ) { this.heldShift = stream.readBoolean(); this.amount = stream.readLong(); } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - if ( player.openContainer instanceof ContainerCraftAmount ) - { - ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; - Object target = cca.getTarget(); - if ( target instanceof IGridHost ) - { - IGridHost gh = (IGridHost) target; - IGridNode gn = gh.getGridNode( ForgeDirection.UNKNOWN ); - if ( gn == null ) - return; - - IGrid g = gn.getGrid(); - if ( g == null || cca.whatToMake == null ) - return; - - Future futureJob = null; - - cca.whatToMake.setStackSize( this.amount ); - - try - { - ICraftingGrid cg = g.getCache( ICraftingGrid.class ); - futureJob = cg.beginCraftingJob( cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.whatToMake, null ); - - ContainerOpenContext context = cca.openContext; - if ( context != null ) - { - TileEntity te = context.getTile(); - Platform.openGUI( player, te, cca.openContext.side, GuiBridge.GUI_CRAFTING_CONFIRM ); - - if ( player.openContainer instanceof ContainerCraftConfirm ) - { - ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer; - ccc.autoStart = this.heldShift; - ccc.job = futureJob; - cca.detectAndSendChanges(); - } - } - - } - catch (Throwable e) - { - if ( futureJob != null ) - futureJob.cancel( true ); - AELog.error( e ); - } - } - } - } - - public PacketCraftRequest(int craftAmt, boolean shift) + public PacketCraftRequest( int craftAmt, boolean shift ) { this.amount = craftAmt; this.heldShift = shift; @@ -121,4 +70,55 @@ public class PacketCraftRequest extends AppEngPacket this.configureWrite( data ); } + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + if( player.openContainer instanceof ContainerCraftAmount ) + { + ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; + Object target = cca.getTarget(); + if( target instanceof IGridHost ) + { + IGridHost gh = (IGridHost) target; + IGridNode gn = gh.getGridNode( ForgeDirection.UNKNOWN ); + if( gn == null ) + return; + + IGrid g = gn.getGrid(); + if( g == null || cca.whatToMake == null ) + return; + + Future futureJob = null; + + cca.whatToMake.setStackSize( this.amount ); + + try + { + ICraftingGrid cg = g.getCache( ICraftingGrid.class ); + futureJob = cg.beginCraftingJob( cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.whatToMake, null ); + + ContainerOpenContext context = cca.openContext; + if( context != null ) + { + TileEntity te = context.getTile(); + Platform.openGUI( player, te, cca.openContext.side, GuiBridge.GUI_CRAFTING_CONFIRM ); + + if( player.openContainer instanceof ContainerCraftConfirm ) + { + ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer; + ccc.autoStart = this.heldShift; + ccc.job = futureJob; + cca.detectAndSendChanges(); + } + } + } + catch( Throwable e ) + { + if( futureJob != null ) + futureJob.cancel( true ); + AELog.error( e ); + } + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java b/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java index d99153073..9e02b5ba8 100644 --- a/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java +++ b/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import java.io.IOException; import io.netty.buffer.ByteBuf; @@ -39,6 +40,7 @@ import appeng.helpers.InventoryAction; import appeng.util.Platform; import appeng.util.item.AEItemStack; + public class PacketInventoryAction extends AppEngPacket { @@ -48,37 +50,87 @@ public class PacketInventoryAction extends AppEngPacket final public IAEItemStack slotItem; // automatic. - public PacketInventoryAction(ByteBuf stream) throws IOException { + public PacketInventoryAction( ByteBuf stream ) throws IOException + { this.action = InventoryAction.values()[stream.readInt()]; this.slot = stream.readInt(); this.id = stream.readLong(); boolean hasItem = stream.readBoolean(); - if ( hasItem ) + if( hasItem ) this.slotItem = AEItemStack.loadItemStackFromPacket( stream ); else this.slotItem = null; } + // api + public PacketInventoryAction( InventoryAction action, int slot, IAEItemStack slotItem ) throws IOException + { + + if( Platform.isClient() ) + throw new RuntimeException( "invalid packet, client cannot post inv actions with stacks." ); + + this.action = action; + this.slot = slot; + this.id = 0; + this.slotItem = slotItem; + + ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + data.writeInt( action.ordinal() ); + data.writeInt( slot ); + data.writeLong( this.id ); + + if( slotItem == null ) + data.writeBoolean( false ); + else + { + data.writeBoolean( true ); + slotItem.writeToPacket( data ); + } + + this.configureWrite( data ); + } + + // api + public PacketInventoryAction( InventoryAction action, int slot, long id ) + { + this.action = action; + this.slot = slot; + this.id = id; + this.slotItem = null; + + ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + data.writeInt( action.ordinal() ); + data.writeInt( slot ); + data.writeLong( id ); + data.writeBoolean( false ); + + this.configureWrite( data ); + } + @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) { EntityPlayerMP sender = (EntityPlayerMP) player; - if ( sender.openContainer instanceof AEBaseContainer ) + if( sender.openContainer instanceof AEBaseContainer ) { AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; - if ( this.action == InventoryAction.AUTO_CRAFT ) + if( this.action == InventoryAction.AUTO_CRAFT ) { ContainerOpenContext context = baseContainer.openContext; - if ( context != null ) + if( context != null ) { TileEntity te = context.getTile(); Platform.openGUI( sender, te, baseContainer.openContext.side, GuiBridge.GUI_CRAFTING_AMOUNT ); - if ( sender.openContainer instanceof ContainerCraftAmount ) + if( sender.openContainer instanceof ContainerCraftAmount ) { ContainerCraftAmount cca = (ContainerCraftAmount) sender.openContainer; - if ( baseContainer.getTargetStack() != null ) + if( baseContainer.getTargetStack() != null ) { cca.craftingItem.putStack( baseContainer.getTargetStack().getItemStack() ); cca.whatToMake = baseContainer.getTargetStack(); @@ -96,62 +148,14 @@ public class PacketInventoryAction extends AppEngPacket } @Override - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) { - if ( this.action == InventoryAction.UPDATE_HAND ) + if( this.action == InventoryAction.UPDATE_HAND ) { - if ( this.slotItem == null ) + if( this.slotItem == null ) ClientHelper.proxy.getPlayers().get( 0 ).inventory.setItemStack( null ); else ClientHelper.proxy.getPlayers().get( 0 ).inventory.setItemStack( this.slotItem.getItemStack() ); } } - - // api - public PacketInventoryAction(InventoryAction action, int slot, IAEItemStack slotItem) throws IOException { - - if ( Platform.isClient() ) - throw new RuntimeException( "invalid packet, client cannot post inv actions with stacks." ); - - this.action = action; - this.slot = slot; - this.id = 0; - this.slotItem = slotItem; - - ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( slot ); - data.writeLong( this.id ); - - if ( slotItem == null ) - data.writeBoolean( false ); - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } - - this.configureWrite( data ); - } - - // api - public PacketInventoryAction(InventoryAction action, int slot, long id) - { - this.action = action; - this.slot = slot; - this.id = id; - this.slotItem = null; - - ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( slot ); - data.writeLong( id ); - data.writeBoolean( false ); - - this.configureWrite( data ); - } } diff --git a/src/main/java/appeng/core/sync/packets/PacketLightning.java b/src/main/java/appeng/core/sync/packets/PacketLightning.java index b8be430e7..24dee29d1 100644 --- a/src/main/java/appeng/core/sync/packets/PacketLightning.java +++ b/src/main/java/appeng/core/sync/packets/PacketLightning.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -34,6 +35,7 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.Platform; + public class PacketLightning extends AppEngPacket { @@ -42,31 +44,15 @@ public class PacketLightning extends AppEngPacket final double z; // automatic. - public PacketLightning(ByteBuf stream) { + public PacketLightning( ByteBuf stream ) + { this.x = stream.readFloat(); this.y = stream.readFloat(); this.z = stream.readFloat(); } - @Override - @SideOnly(Side.CLIENT) - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - try - { - if ( Platform.isClient() && AEConfig.instance.enableEffects ) - { - LightningFX fx = new LightningFX( ClientHelper.proxy.getWorld(), this.x, this.y, this.z, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - catch (Exception ignored) - { - } - } - // api - public PacketLightning(double x, double y, double z) + public PacketLightning( double x, double y, double z ) { this.x = x; this.y = y; @@ -82,4 +68,20 @@ public class PacketLightning extends AppEngPacket this.configureWrite( data ); } + @Override + @SideOnly( Side.CLIENT ) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + try + { + if( Platform.isClient() && AEConfig.instance.enableEffects ) + { + LightningFX fx = new LightningFX( ClientHelper.proxy.getWorld(), this.x, this.y, this.z, 0.0f, 0.0f, 0.0f ); + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + } + catch( Exception ignored ) + { + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java b/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java index 10c5bb8b9..964e0e7a7 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java +++ b/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -34,6 +35,7 @@ import appeng.client.render.effects.MatterCannonFX; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; + public class PacketMatterCannon extends AppEngPacket { @@ -46,7 +48,7 @@ public class PacketMatterCannon extends AppEngPacket final byte len; // automatic. - public PacketMatterCannon(ByteBuf stream) + public PacketMatterCannon( ByteBuf stream ) { this.x = stream.readFloat(); this.y = stream.readFloat(); @@ -57,28 +59,8 @@ public class PacketMatterCannon extends AppEngPacket this.len = stream.readByte(); } - @Override - @SideOnly(Side.CLIENT) - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - try - { - - World world = FMLClientHandler.instance().getClient().theWorld; - for (int a = 1; a < this.len; a++) - { - MatterCannonFX fx = new MatterCannonFX( world, this.x + this.dx * a, this.y + this.dy * a, this.z + this.dz * a, Items.diamond ); - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - catch (Exception ignored) - { - } - } - // api - public PacketMatterCannon(double x, double y, double z, float dx, float dy, float dz, byte len) + public PacketMatterCannon( double x, double y, double z, float dx, float dy, float dz, byte len ) { float dl = dx * dx + dy * dy + dz * dz; float dlz = (float) Math.sqrt( dl ); @@ -105,4 +87,23 @@ public class PacketMatterCannon extends AppEngPacket this.configureWrite( data ); } + @Override + @SideOnly( Side.CLIENT ) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + try + { + + World world = FMLClientHandler.instance().getClient().theWorld; + for( int a = 1; a < this.len; a++ ) + { + MatterCannonFX fx = new MatterCannonFX( world, this.x + this.dx * a, this.y + this.dy * a, this.z + this.dz * a, Items.diamond ); + + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + } + catch( Exception ignored ) + { + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java b/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java index 4f61659b6..51578594a 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java +++ b/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -31,6 +32,7 @@ import appeng.core.CommonHelper; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; + public class PacketMockExplosion extends AppEngPacket { @@ -38,16 +40,8 @@ public class PacketMockExplosion extends AppEngPacket final public double y; final public double z; - @Override - @SideOnly(Side.CLIENT) - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - World world = CommonHelper.proxy.getWorld(); - world.spawnParticle( "largeexplode", this.x, this.y, this.z, 1.0D, 0.0D, 0.0D ); - } - // automatic. - public PacketMockExplosion(ByteBuf stream) + public PacketMockExplosion( ByteBuf stream ) { this.x = stream.readDouble(); this.y = stream.readDouble(); @@ -55,7 +49,7 @@ public class PacketMockExplosion extends AppEngPacket } // api - public PacketMockExplosion(double x, double y, double z) + public PacketMockExplosion( double x, double y, double z ) { this.x = x; this.y = y; @@ -71,4 +65,11 @@ public class PacketMockExplosion extends AppEngPacket this.configureWrite( data ); } + @Override + @SideOnly( Side.CLIENT ) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + World world = CommonHelper.proxy.getWorld(); + world.spawnParticle( "largeexplode", this.x, this.y, this.z, 1.0D, 0.0D, 0.0D ); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMultiPart.java b/src/main/java/appeng/core/sync/packets/PacketMultiPart.java index 90e039f66..76ad86d4a 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMultiPart.java +++ b/src/main/java/appeng/core/sync/packets/PacketMultiPart.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -31,25 +32,15 @@ import appeng.core.sync.network.INetworkInfo; import appeng.integration.IntegrationType; import appeng.integration.abstraction.IFMP; + public class PacketMultiPart extends AppEngPacket { // automatic. - public PacketMultiPart(ByteBuf stream) + public PacketMultiPart( ByteBuf stream ) { } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - IFMP fmp = (IFMP) AppEng.instance.getIntegration( IntegrationType.FMP ); - if ( fmp != null ) - { - EntityPlayerMP sender = (EntityPlayerMP) player; - MinecraftForge.EVENT_BUS.post( fmp.newFMPPacketEvent( sender ) ); // when received it just posts this event. - } - } - // api public PacketMultiPart() { @@ -60,4 +51,14 @@ public class PacketMultiPart extends AppEngPacket this.configureWrite( data ); } + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + IFMP fmp = (IFMP) AppEng.instance.getIntegration( IntegrationType.FMP ); + if( fmp != null ) + { + EntityPlayerMP sender = (EntityPlayerMP) player; + MinecraftForge.EVENT_BUS.post( fmp.newFMPPacketEvent( sender ) ); // when received it just posts this event. + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java b/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java index 862e3b538..a9266e3cf 100644 --- a/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java +++ b/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java @@ -69,16 +69,16 @@ public class PacketNEIRecipe extends AppEngPacket ByteArrayInputStream bytes = new ByteArrayInputStream( stream.array() ); bytes.skip( stream.readerIndex() ); NBTTagCompound comp = CompressedStreamTools.readCompressed( bytes ); - if ( comp != null ) + if( comp != null ) { this.recipe = new ItemStack[9][]; - for ( int x = 0; x < this.recipe.length; x++ ) + for( int x = 0; x < this.recipe.length; x++ ) { NBTTagList list = comp.getTagList( "#" + x, 10 ); - if ( list.tagCount() > 0 ) + if( list.tagCount() > 0 ) { this.recipe[x] = new ItemStack[list.tagCount()]; - for ( int y = 0; y < list.tagCount(); y++ ) + for( int y = 0; y < list.tagCount(); y++ ) { this.recipe[x][y] = ItemStack.loadItemStackFromNBT( list.getCompoundTagAt( y ) ); } @@ -87,20 +87,36 @@ public class PacketNEIRecipe extends AppEngPacket } } + // api + public PacketNEIRecipe( NBTTagCompound recipe ) throws IOException + { + ByteBuf data = Unpooled.buffer(); + + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream outputStream = new DataOutputStream( bytes ); + + data.writeInt( this.getPacketID() ); + + CompressedStreamTools.writeCompressed( recipe, outputStream ); + data.writeBytes( bytes.toByteArray() ); + + this.configureWrite( data ); + } + @Override public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) { - EntityPlayerMP pmp = ( EntityPlayerMP ) player; + EntityPlayerMP pmp = (EntityPlayerMP) player; Container con = pmp.openContainer; - if ( con instanceof IContainerCraftingPacket ) + if( con instanceof IContainerCraftingPacket ) { - IContainerCraftingPacket cct = ( IContainerCraftingPacket ) con; + IContainerCraftingPacket cct = (IContainerCraftingPacket) con; IGridNode node = cct.getNetworkNode(); - if ( node != null ) + if( node != null ) { IGrid grid = node.getGrid(); - if ( grid == null ) + if( grid == null ) return; IStorageGrid inv = grid.getCache( IStorageGrid.class ); @@ -111,12 +127,12 @@ public class PacketNEIRecipe extends AppEngPacket Actionable realForFake = cct.useRealItems() ? Actionable.MODULATE : Actionable.SIMULATE; - if ( inv != null && this.recipe != null && security != null ) + if( inv != null && this.recipe != null && security != null ) { InventoryCrafting testInv = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for ( int x = 0; x < 9; x++ ) + for( int x = 0; x < 9; x++ ) { - if ( this.recipe[x] != null && this.recipe[x].length > 0 ) + if( this.recipe[x] != null && this.recipe[x].length > 0 ) { testInv.setInventorySlotContents( x, this.recipe[x][0] ); } @@ -124,35 +140,34 @@ public class PacketNEIRecipe extends AppEngPacket IRecipe r = Platform.findMatchingRecipe( testInv, pmp.worldObj ); - if ( r != null && security.hasPermission( player, SecurityPermissions.EXTRACT ) ) + if( r != null && security.hasPermission( player, SecurityPermissions.EXTRACT ) ) { ItemStack is = r.getCraftingResult( testInv ); - if ( is != null ) + if( is != null ) { IMEMonitor storage = inv.getItemInventory(); IItemList all = storage.getStorageList(); IPartitionList filter = ItemViewCell.createFilter( cct.getViewCells() ); - for ( int x = 0; x < craftMatrix.getSizeInventory(); x++ ) + for( int x = 0; x < craftMatrix.getSizeInventory(); x++ ) { ItemStack PatternItem = testInv.getStackInSlot( x ); ItemStack currentItem = craftMatrix.getStackInSlot( x ); - if ( currentItem != null ) + if( currentItem != null ) { testInv.setInventorySlotContents( x, currentItem ); ItemStack newItemStack = r.matches( testInv, pmp.worldObj ) ? r.getCraftingResult( testInv ) : null; testInv.setInventorySlotContents( x, PatternItem ); - if ( newItemStack == null || !Platform.isSameItemPrecise( newItemStack, is ) ) + if( newItemStack == null || !Platform.isSameItemPrecise( newItemStack, is ) ) { IAEItemStack in = AEItemStack.create( currentItem ); - if ( in != null ) + if( in != null ) { - IAEItemStack out = realForFake == Actionable.SIMULATE ? null : Platform.poweredInsert( energy, storage, in, - cct.getSource() ); - if ( out != null ) + IAEItemStack out = realForFake == Actionable.SIMULATE ? null : Platform.poweredInsert( energy, storage, in, cct.getSource() ); + if( out != null ) craftMatrix.setInventorySlotContents( x, out.getItemStack() ); else craftMatrix.setInventorySlotContents( x, null ); @@ -163,26 +178,25 @@ public class PacketNEIRecipe extends AppEngPacket } // True if we need to fetch an item for the recipe - if ( PatternItem != null && currentItem == null ) + if( PatternItem != null && currentItem == null ) { // Grab from network by recipe - ItemStack whichItem = Platform.extractItemsByRecipe( energy, cct.getSource(), storage, player.worldObj, r, is, testInv, - PatternItem, x, all, realForFake, filter ); + ItemStack whichItem = Platform.extractItemsByRecipe( energy, cct.getSource(), storage, player.worldObj, r, is, testInv, PatternItem, x, all, realForFake, filter ); // If that doesn't get it, grab exact items from network (?) // TODO see if this code is necessary - if ( whichItem == null ) + if( whichItem == null ) { - for ( int y = 0; y < this.recipe[x].length; y++ ) + for( int y = 0; y < this.recipe[x].length; y++ ) { IAEItemStack request = AEItemStack.create( this.recipe[x][y] ); - if ( request != null ) + if( request != null ) { - if ( filter == null || filter.isListed( request ) ) + if( filter == null || filter.isListed( request ) ) { request.setStackSize( 1 ); IAEItemStack out = Platform.poweredExtraction( energy, storage, request, cct.getSource() ); - if ( out != null ) + if( out != null ) { whichItem = out.getItemStack(); break; @@ -193,18 +207,18 @@ public class PacketNEIRecipe extends AppEngPacket } // If that doesn't work, grab from the player's inventory - if ( whichItem == null && playerInventory != null ) + if( whichItem == null && playerInventory != null ) { - for ( int y = 0; y < this.recipe[x].length; y++ ) + for( int y = 0; y < this.recipe[x].length; y++ ) { ItemStack playerItemStack = null; - for ( int i = 0; i < playerInventory.getSizeInventory(); i++ ) + for( int i = 0; i < playerInventory.getSizeInventory(); i++ ) { // check if the item in slot y matches the required item. playerItemStack = playerInventory.getStackInSlot( i ); - if ( playerItemStack != null && this.recipe[x][y] != null && playerItemStack.getItem() == this.recipe[x][y].getItem() ) + if( playerItemStack != null && this.recipe[x][y] != null && playerItemStack.getItem() == this.recipe[x][y].getItem() ) { - if ( realForFake == Actionable.SIMULATE ) + if( realForFake == Actionable.SIMULATE ) { whichItem = playerInventory.getStackInSlot( i ).copy(); whichItem.stackSize = 1; @@ -229,20 +243,4 @@ public class PacketNEIRecipe extends AppEngPacket } } } - - // api - public PacketNEIRecipe( NBTTagCompound recipe ) throws IOException - { - ByteBuf data = Unpooled.buffer(); - - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - DataOutputStream outputStream = new DataOutputStream( bytes ); - - data.writeInt( this.getPacketID() ); - - CompressedStreamTools.writeCompressed( recipe, outputStream ); - data.writeBytes( bytes.toByteArray() ); - - this.configureWrite( data ); - } } diff --git a/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java b/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java index b07ea1908..1b4d225af 100644 --- a/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java +++ b/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -31,33 +32,20 @@ import appeng.core.AEConfig; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; + public class PacketNewStorageDimension extends AppEngPacket { final int newDim; // automatic. - public PacketNewStorageDimension(ByteBuf stream) + public PacketNewStorageDimension( ByteBuf stream ) { this.newDim = stream.readInt(); } - @Override - @SideOnly(Side.CLIENT) - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - try - { - DimensionManager.registerDimension( this.newDim, AEConfig.instance.storageProviderID ); - } - catch (IllegalArgumentException iae) - { - // ok! - } - } - // api - public PacketNewStorageDimension(int newDim) + public PacketNewStorageDimension( int newDim ) { this.newDim = newDim; @@ -69,4 +57,17 @@ public class PacketNewStorageDimension extends AppEngPacket this.configureWrite( data ); } + @Override + @SideOnly( Side.CLIENT ) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + try + { + DimensionManager.registerDimension( this.newDim, AEConfig.instance.storageProviderID ); + } + catch( IllegalArgumentException iae ) + { + // ok! + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java b/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java index 9d5b059bc..28a33af7f 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java +++ b/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -29,6 +30,7 @@ import appeng.core.sync.network.INetworkInfo; import appeng.hooks.TickHandler; import appeng.hooks.TickHandler.PlayerColor; + public class PacketPaintedEntity extends AppEngPacket { @@ -37,30 +39,31 @@ public class PacketPaintedEntity extends AppEngPacket private int ticks; // automatic. - public PacketPaintedEntity(ByteBuf stream) + public PacketPaintedEntity( ByteBuf stream ) { this.entityId = stream.readInt(); this.myColor = AEColor.values()[stream.readByte()]; this.ticks = stream.readInt(); } - @Override - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - PlayerColor pc = new PlayerColor( this.entityId, this.myColor, this.ticks ); - TickHandler.INSTANCE.getPlayerColors().put( this.entityId, pc ); - } - // api - public PacketPaintedEntity(int myEntity, AEColor myColor, int ticksLeft) { + public PacketPaintedEntity( int myEntity, AEColor myColor, int ticksLeft ) + { ByteBuf data = Unpooled.buffer(); data.writeInt( this.getPacketID() ); data.writeInt( this.entityId = myEntity ); - data.writeByte( (this.myColor = myColor).ordinal() ); + data.writeByte( ( this.myColor = myColor ).ordinal() ); data.writeInt( ticksLeft ); this.configureWrite( data ); } + + @Override + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + PlayerColor pc = new PlayerColor( this.entityId, this.myColor, this.ticks ); + TickHandler.INSTANCE.getPlayerColors().put( this.entityId, pc ); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java b/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java index 8619dd0c5..4b7d064aa 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java +++ b/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -29,6 +30,7 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.parts.PartPlacement; + public class PacketPartPlacement extends AppEngPacket { @@ -39,7 +41,7 @@ public class PacketPartPlacement extends AppEngPacket float eyeHeight; // automatic. - public PacketPartPlacement(ByteBuf stream) + public PacketPartPlacement( ByteBuf stream ) { this.x = stream.readInt(); this.y = stream.readInt(); @@ -48,18 +50,8 @@ public class PacketPartPlacement extends AppEngPacket this.eyeHeight = stream.readFloat(); } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - EntityPlayerMP sender = (EntityPlayerMP) player; - CommonHelper.proxy.updateRenderMode( sender ); - PartPlacement.eyeHeight = this.eyeHeight; - PartPlacement.place( sender.getHeldItem(), this.x, this.y, this.z, this.face, sender, sender.worldObj, PartPlacement.PlaceType.INTERACT_FIRST_PASS, 0 ); - CommonHelper.proxy.updateRenderMode( null ); - } - // api - public PacketPartPlacement(int x, int y, int z, int face, float eyeHeight ) + public PacketPartPlacement( int x, int y, int z, int face, float eyeHeight ) { ByteBuf data = Unpooled.buffer(); @@ -73,4 +65,13 @@ public class PacketPartPlacement extends AppEngPacket this.configureWrite( data ); } + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + EntityPlayerMP sender = (EntityPlayerMP) player; + CommonHelper.proxy.updateRenderMode( sender ); + PartPlacement.eyeHeight = this.eyeHeight; + PartPlacement.place( sender.getHeldItem(), this.x, this.y, this.z, this.face, sender, sender.worldObj, PartPlacement.PlaceType.INTERACT_FIRST_PASS, 0 ); + CommonHelper.proxy.updateRenderMode( null ); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPartialItem.java b/src/main/java/appeng/core/sync/packets/PacketPartialItem.java index ac0e60695..a09e5f5ef 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPartialItem.java +++ b/src/main/java/appeng/core/sync/packets/PacketPartialItem.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -27,6 +28,7 @@ import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; + public class PacketPartialItem extends AppEngPacket { @@ -34,28 +36,19 @@ public class PacketPartialItem extends AppEngPacket final byte[] data; // automatic. - public PacketPartialItem(ByteBuf stream) + public PacketPartialItem( ByteBuf stream ) { this.pageNum = stream.readShort(); stream.readBytes( this.data = new byte[stream.readableBytes()] ); } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - if ( player.openContainer instanceof AEBaseContainer ) - { - ((AEBaseContainer) player.openContainer).postPartial( this ); - } - } - // api - public PacketPartialItem(int page, int maxPages, byte[] buf) + public PacketPartialItem( int page, int maxPages, byte[] buf ) { ByteBuf data = Unpooled.buffer(); - this.pageNum = (short) (page | (maxPages << 8)); + this.pageNum = (short) ( page | ( maxPages << 8 ) ); this.data = buf; data.writeInt( this.getPacketID() ); data.writeShort( this.pageNum ); @@ -64,6 +57,15 @@ public class PacketPartialItem extends AppEngPacket this.configureWrite( data ); } + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + if( player.openContainer instanceof AEBaseContainer ) + { + ( (AEBaseContainer) player.openContainer ).postPartial( this ); + } + } + public int getPageCount() { return this.pageNum >> 8; @@ -74,7 +76,7 @@ public class PacketPartialItem extends AppEngPacket return this.data.length; } - public int write(byte[] buffer, int cursor) + public int write( byte[] buffer, int cursor ) { System.arraycopy( this.data, 0, buffer, cursor, this.data.length ); return cursor + this.data.length; diff --git a/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java b/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java index 334dff55d..59be00d2c 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java +++ b/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import java.io.IOException; import io.netty.buffer.ByteBuf; @@ -34,6 +35,7 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.item.AEItemStack; + public class PacketPatternSlot extends AppEngPacket { @@ -43,51 +45,31 @@ public class PacketPatternSlot extends AppEngPacket final public boolean shift; - public IAEItemStack readItem(ByteBuf stream) throws IOException - { - boolean hasItem = stream.readBoolean(); - - if ( hasItem ) - return AEItemStack.loadItemStackFromPacket( stream ); - - return null; - } - // automatic. - public PacketPatternSlot(ByteBuf stream) throws IOException { + public PacketPatternSlot( ByteBuf stream ) throws IOException + { this.shift = stream.readBoolean(); this.slotItem = this.readItem( stream ); - for (int x = 0; x < 9; x++) + for( int x = 0; x < 9; x++ ) this.pattern[x] = this.readItem( stream ); } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) + public IAEItemStack readItem( ByteBuf stream ) throws IOException { - EntityPlayerMP sender = (EntityPlayerMP) player; - if ( sender.openContainer instanceof ContainerPatternTerm ) - { - ContainerPatternTerm patternTerminal = (ContainerPatternTerm) sender.openContainer; - patternTerminal.craftOrGetItem( this ); - } - } + boolean hasItem = stream.readBoolean(); - private void writeItem(IAEItemStack slotItem, ByteBuf data) throws IOException - { - if ( slotItem == null ) - data.writeBoolean( false ); - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } + if( hasItem ) + return AEItemStack.loadItemStackFromPacket( stream ); + + return null; } // api - public PacketPatternSlot(IInventory pat, IAEItemStack slotItem, boolean shift) throws IOException { + public PacketPatternSlot( IInventory pat, IAEItemStack slotItem, boolean shift ) throws IOException + { this.slotItem = slotItem; this.shift = shift; @@ -99,7 +81,7 @@ public class PacketPatternSlot extends AppEngPacket data.writeBoolean( shift ); this.writeItem( slotItem, data ); - for (int x = 0; x < 9; x++) + for( int x = 0; x < 9; x++ ) { this.pattern[x] = AEApi.instance().storage().createItemStack( pat.getStackInSlot( x ) ); this.writeItem( this.pattern[x], data ); @@ -108,4 +90,25 @@ public class PacketPatternSlot extends AppEngPacket this.configureWrite( data ); } + private void writeItem( IAEItemStack slotItem, ByteBuf data ) throws IOException + { + if( slotItem == null ) + data.writeBoolean( false ); + else + { + data.writeBoolean( true ); + slotItem.writeToPacket( data ); + } + } + + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + EntityPlayerMP sender = (EntityPlayerMP) player; + if( sender.openContainer instanceof ContainerPatternTerm ) + { + ContainerPatternTerm patternTerminal = (ContainerPatternTerm) sender.openContainer; + patternTerminal.craftOrGetItem( this ); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketProgressBar.java b/src/main/java/appeng/core/sync/packets/PacketProgressBar.java index 226107e01..fbc7c75b6 100644 --- a/src/main/java/appeng/core/sync/packets/PacketProgressBar.java +++ b/src/main/java/appeng/core/sync/packets/PacketProgressBar.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -28,6 +29,7 @@ import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; + public class PacketProgressBar extends AppEngPacket { @@ -35,30 +37,14 @@ public class PacketProgressBar extends AppEngPacket final long value; // automatic. - public PacketProgressBar(ByteBuf stream) + public PacketProgressBar( ByteBuf stream ) { this.id = stream.readShort(); this.value = stream.readLong(); } - @Override - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - Container c = player.openContainer; - if ( c instanceof AEBaseContainer ) - ((AEBaseContainer) c).updateFullProgressBar( this.id, this.value ); - } - - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - Container c = player.openContainer; - if ( c instanceof AEBaseContainer ) - ((AEBaseContainer) c).updateFullProgressBar( this.id, this.value ); - } - // api - public PacketProgressBar(int short_id, long value) + public PacketProgressBar( int short_id, long value ) { this.id = (short) short_id; this.value = value; @@ -71,4 +57,20 @@ public class PacketProgressBar extends AppEngPacket this.configureWrite( data ); } + + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + Container c = player.openContainer; + if( c instanceof AEBaseContainer ) + ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); + } + + @Override + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + Container c = player.openContainer; + if( c instanceof AEBaseContainer ) + ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java b/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java index a0bbc9368..cedae9749 100644 --- a/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java +++ b/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -27,6 +28,7 @@ import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; + public class PacketSwapSlots extends AppEngPacket { @@ -34,23 +36,14 @@ public class PacketSwapSlots extends AppEngPacket final int slotB; // automatic. - public PacketSwapSlots(ByteBuf stream) + public PacketSwapSlots( ByteBuf stream ) { this.slotA = stream.readInt(); this.slotB = stream.readInt(); } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - if ( player != null && player.openContainer instanceof AEBaseContainer ) - { - ((AEBaseContainer) player.openContainer).swapSlotContents( this.slotA, this.slotB ); - } - } - // api - public PacketSwapSlots(int slotA, int slotB) + public PacketSwapSlots( int slotA, int slotB ) { ByteBuf data = Unpooled.buffer(); @@ -60,4 +53,13 @@ public class PacketSwapSlots extends AppEngPacket this.configureWrite( data ); } + + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + if( player != null && player.openContainer instanceof AEBaseContainer ) + { + ( (AEBaseContainer) player.openContainer ).swapSlotContents( this.slotA, this.slotB ); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java b/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java index b74bceee3..500626219 100644 --- a/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java +++ b/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -33,45 +34,24 @@ import appeng.core.sync.GuiBridge; import appeng.core.sync.network.INetworkInfo; import appeng.util.Platform; + public class PacketSwitchGuis extends AppEngPacket { final GuiBridge newGui; // automatic. - public PacketSwitchGuis(ByteBuf stream) + public PacketSwitchGuis( ByteBuf stream ) { this.newGui = GuiBridge.values()[stream.readInt()]; } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - Container c = player.openContainer; - if ( c instanceof AEBaseContainer ) - { - AEBaseContainer bc = (AEBaseContainer) c; - ContainerOpenContext context = bc.openContext; - if ( context != null ) - { - TileEntity te = context.getTile(); - Platform.openGUI( player, te, context.side, this.newGui ); - } - } - } - - @Override - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - AEBaseGui.switchingGuis = true; - } - // api - public PacketSwitchGuis(GuiBridge newGui) + public PacketSwitchGuis( GuiBridge newGui ) { this.newGui = newGui; - if ( Platform.isClient() ) + if( Platform.isClient() ) AEBaseGui.switchingGuis = true; ByteBuf data = Unpooled.buffer(); @@ -81,4 +61,26 @@ public class PacketSwitchGuis extends AppEngPacket this.configureWrite( data ); } + + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + Container c = player.openContainer; + if( c instanceof AEBaseContainer ) + { + AEBaseContainer bc = (AEBaseContainer) c; + ContainerOpenContext context = bc.openContext; + if( context != null ) + { + TileEntity te = context.getTile(); + Platform.openGUI( player, te, context.side, this.newGui ); + } + } + } + + @Override + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + AEBaseGui.switchingGuis = true; + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java b/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java index bc21ff251..21931d0c1 100644 --- a/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java +++ b/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -40,17 +41,18 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.util.Platform; + public class PacketTransitionEffect extends AppEngPacket { + final public boolean mode; final double x; final double y; final double z; final ForgeDirection d; - final public boolean mode; // automatic. - public PacketTransitionEffect(ByteBuf stream) + public PacketTransitionEffect( ByteBuf stream ) { this.x = stream.readFloat(); this.y = stream.readFloat(); @@ -59,44 +61,8 @@ public class PacketTransitionEffect extends AppEngPacket this.mode = stream.readBoolean(); } - @Override - @SideOnly(Side.CLIENT) - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - World world = ClientHelper.proxy.getWorld(); - - for (int zz = 0; zz < (this.mode ? 32 : 8); zz++) - if ( CommonHelper.proxy.shouldAddParticles( Platform.getRandom() ) ) - { - EnergyFx fx = new EnergyFx( world, this.x + (this.mode ? (Platform.getRandomInt() % 100) * 0.01 : (Platform.getRandomInt() % 100) * 0.005 - 0.25), this.y - + (this.mode ? (Platform.getRandomInt() % 100) * 0.01 : (Platform.getRandomInt() % 100) * 0.005 - 0.25), this.z - + (this.mode ? (Platform.getRandomInt() % 100) * 0.01 : (Platform.getRandomInt() % 100) * 0.005 - 0.25), Items.diamond ); - - if ( !this.mode ) - fx.fromItem( this.d ); - - fx.motionX = -0.1 * this.d.offsetX; - fx.motionY = -0.1 * this.d.offsetY; - fx.motionZ = -0.1 * this.d.offsetZ; - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - if ( this.mode ) - { - Block block = world.getBlock( (int) this.x, (int) this.y, (int) this.z ); - - Minecraft - .getMinecraft() - .getSoundHandler() - .playSound( - new PositionedSoundRecord( new ResourceLocation( block.stepSound.getBreakSound() ), (block.stepSound.getVolume() + 1.0F) / 2.0F, - block.stepSound.getPitch() * 0.8F, (float) this.x + 0.5F, (float) this.y + 0.5F, (float) this.z + 0.5F ) ); - } - } - // api - public PacketTransitionEffect(double x, double y, double z, ForgeDirection dir, boolean wasBlock) + public PacketTransitionEffect( double x, double y, double z, ForgeDirection dir, boolean wasBlock ) { this.x = x; this.y = y; @@ -116,4 +82,32 @@ public class PacketTransitionEffect extends AppEngPacket this.configureWrite( data ); } + @Override + @SideOnly( Side.CLIENT ) + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + World world = ClientHelper.proxy.getWorld(); + + for( int zz = 0; zz < ( this.mode ? 32 : 8 ); zz++ ) + if( CommonHelper.proxy.shouldAddParticles( Platform.getRandom() ) ) + { + EnergyFx fx = new EnergyFx( world, this.x + ( this.mode ? ( Platform.getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), this.y + ( this.mode ? ( Platform.getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), this.z + ( this.mode ? ( Platform.getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), Items.diamond ); + + if( !this.mode ) + fx.fromItem( this.d ); + + fx.motionX = -0.1 * this.d.offsetX; + fx.motionY = -0.1 * this.d.offsetY; + fx.motionZ = -0.1 * this.d.offsetZ; + + Minecraft.getMinecraft().effectRenderer.addEffect( fx ); + } + + if( this.mode ) + { + Block block = world.getBlock( (int) this.x, (int) this.y, (int) this.z ); + + Minecraft.getMinecraft().getSoundHandler().playSound( new PositionedSoundRecord( new ResourceLocation( block.stepSound.getBreakSound() ), ( block.stepSound.getVolume() + 1.0F ) / 2.0F, block.stepSound.getPitch() * 0.8F, (float) this.x + 0.5F, (float) this.y + 0.5F, (float) this.z + 0.5F ) ); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketValueConfig.java b/src/main/java/appeng/core/sync/packets/PacketValueConfig.java index 8d1378c3c..1069246f7 100644 --- a/src/main/java/appeng/core/sync/packets/PacketValueConfig.java +++ b/src/main/java/appeng/core/sync/packets/PacketValueConfig.java @@ -18,6 +18,7 @@ package appeng.core.sync.packets; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; @@ -54,6 +55,7 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.helpers.IMouseWheelItem; + public class PacketValueConfig extends AppEngPacket { @@ -61,198 +63,17 @@ public class PacketValueConfig extends AppEngPacket final public String Value; // automatic. - public PacketValueConfig(ByteBuf stream) throws IOException { + public PacketValueConfig( ByteBuf stream ) throws IOException + { DataInputStream dis = new DataInputStream( new ByteArrayInputStream( stream.array(), stream.readerIndex(), stream.readableBytes() ) ); this.Name = dis.readUTF(); this.Value = dis.readUTF(); // dis.close(); } - @Override - public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) - { - Container c = player.openContainer; - - if ( this.Name.equals( "Item" ) && player.getHeldItem() != null && player.getHeldItem().getItem() instanceof IMouseWheelItem ) - { - ItemStack is = player.getHeldItem(); - IMouseWheelItem si = (IMouseWheelItem) is.getItem(); - si.onWheel( is, this.Value.equals( "WheelUp" ) ); - } - else if ( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftingStatus ) - { - ContainerCraftingStatus qk = (ContainerCraftingStatus) c; - qk.cycleCpu( this.Value.equals( "Next" ) ); - } - else if ( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftConfirm ) - { - ContainerCraftConfirm qk = (ContainerCraftConfirm) c; - qk.cycleCpu( this.Value.equals( "Next" ) ); - } - else if ( this.Name.equals( "Terminal.Start" ) && c instanceof ContainerCraftConfirm ) - { - ContainerCraftConfirm qk = (ContainerCraftConfirm) c; - qk.startJob(); - } - else if ( this.Name.equals( "TileCrafting.Cancel" ) && c instanceof ContainerCraftingCPU ) - { - ContainerCraftingCPU qk = (ContainerCraftingCPU) c; - qk.cancelCrafting(); - } - else if ( this.Name.equals( "QuartzKnife.Name" ) && c instanceof ContainerQuartzKnife ) - { - ContainerQuartzKnife qk = (ContainerQuartzKnife) c; - qk.setName( this.Value ); - } - else if ( this.Name.equals( "TileSecurity.ToggleOption" ) && c instanceof ContainerSecurity ) - { - ContainerSecurity sc = (ContainerSecurity) c; - sc.toggleSetting( this.Value, player ); - } - else if ( this.Name.equals( "PriorityHost.Priority" ) && c instanceof ContainerPriority ) - { - ContainerPriority pc = (ContainerPriority) c; - pc.setPriority( Integer.parseInt( this.Value ), player ); - } - else if ( this.Name.equals( "LevelEmitter.Value" ) && c instanceof ContainerLevelEmitter ) - { - ContainerLevelEmitter lvc = (ContainerLevelEmitter) c; - lvc.setLevel( Long.parseLong( this.Value ), player ); - } - else if ( this.Name.startsWith( "PatternTerminal." ) && c instanceof ContainerPatternTerm ) - { - ContainerPatternTerm cpt = (ContainerPatternTerm) c; - if ( this.Name.equals( "PatternTerminal.CraftMode" ) ) - { - cpt.ct.setCraftingRecipe( this.Value.equals( "1" ) ); - } - else if ( this.Name.equals( "PatternTerminal.Encode" ) ) - { - cpt.encode(); - } - else if ( this.Name.equals( "PatternTerminal.Clear" ) ) - { - cpt.clear(); - } - } - else if ( this.Name.startsWith( "StorageBus." ) && c instanceof ContainerStorageBus ) - { - ContainerStorageBus ccw = (ContainerStorageBus) c; - if ( this.Name.equals( "StorageBus.Action" ) ) - { - if ( this.Value.equals( "Partition" ) ) - { - ccw.partition(); - } - else if ( this.Value.equals( "Clear" ) ) - { - ccw.clear(); - } - } - } - else if ( this.Name.startsWith( "CellWorkbench." ) && c instanceof ContainerCellWorkbench ) - { - ContainerCellWorkbench ccw = (ContainerCellWorkbench) c; - if ( this.Name.equals( "CellWorkbench.Action" ) ) - { - if ( this.Value.equals( "CopyMode" ) ) - { - ccw.nextCopyMode(); - } - else if ( this.Value.equals( "Partition" ) ) - { - ccw.partition(); - } - else if ( this.Value.equals( "Clear" ) ) - { - ccw.clear(); - } - } - else if ( this.Name.equals( "CellWorkbench.Fuzzy" ) ) - { - ccw.setFuzzy( FuzzyMode.valueOf( this.Value ) ); - } - } - else if ( c instanceof ContainerNetworkTool ) - { - if ( this.Name.equals( "NetworkTool" ) && this.Value.equals( "Toggle" ) ) - { - ((ContainerNetworkTool) c).toggleFacadeMode(); - } - } - else if ( c instanceof IConfigurableObject ) - { - IConfigManager cm = ((IConfigurableObject) c).getConfigManager(); - - for (Settings e : cm.getSettings()) - { - if ( e.name().equals( this.Name ) ) - { - Enum def = cm.getSetting( e ); - - try - { - cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); - } - catch (IllegalArgumentException err) - { - // :P - } - - break; - } - } - } - - } - - @Override - public void clientPacketData(INetworkInfo network, AppEngPacket packet, EntityPlayer player) - { - Container c = player.openContainer; - - if ( this.Name.equals( "CustomName" ) && c instanceof AEBaseContainer ) - { - ((AEBaseContainer) c).customName = this.Value; - } - else if ( this.Name.startsWith( "SyncDat." ) ) - { - ((AEBaseContainer) c).stringSync( Integer.parseInt( this.Name.substring( 8 ) ), this.Value ); - } - else if ( this.Name.equals( "CraftingStatus" ) && this.Value.equals( "Clear" ) ) - { - GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if ( gs instanceof GuiCraftingCPU ) - ((GuiCraftingCPU) gs).clearItems(); - } - else if ( c instanceof IConfigurableObject ) - { - IConfigManager cm = ((IConfigurableObject) c).getConfigManager(); - - for (Settings e : cm.getSettings()) - { - if ( e.name().equals( this.Name ) ) - { - Enum def = cm.getSetting( e ); - - try - { - cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); - } - catch (IllegalArgumentException err) - { - // :P - } - - break; - } - } - } - - } - // api - public PacketValueConfig(String Name, String Value) throws IOException { + public PacketValueConfig( String Name, String Value ) throws IOException + { this.Name = Name; this.Value = Value; @@ -270,4 +91,185 @@ public class PacketValueConfig extends AppEngPacket this.configureWrite( data ); } + + @Override + public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) + { + Container c = player.openContainer; + + if( this.Name.equals( "Item" ) && player.getHeldItem() != null && player.getHeldItem().getItem() instanceof IMouseWheelItem ) + { + ItemStack is = player.getHeldItem(); + IMouseWheelItem si = (IMouseWheelItem) is.getItem(); + si.onWheel( is, this.Value.equals( "WheelUp" ) ); + } + else if( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftingStatus ) + { + ContainerCraftingStatus qk = (ContainerCraftingStatus) c; + qk.cycleCpu( this.Value.equals( "Next" ) ); + } + else if( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftConfirm ) + { + ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.cycleCpu( this.Value.equals( "Next" ) ); + } + else if( this.Name.equals( "Terminal.Start" ) && c instanceof ContainerCraftConfirm ) + { + ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.startJob(); + } + else if( this.Name.equals( "TileCrafting.Cancel" ) && c instanceof ContainerCraftingCPU ) + { + ContainerCraftingCPU qk = (ContainerCraftingCPU) c; + qk.cancelCrafting(); + } + else if( this.Name.equals( "QuartzKnife.Name" ) && c instanceof ContainerQuartzKnife ) + { + ContainerQuartzKnife qk = (ContainerQuartzKnife) c; + qk.setName( this.Value ); + } + else if( this.Name.equals( "TileSecurity.ToggleOption" ) && c instanceof ContainerSecurity ) + { + ContainerSecurity sc = (ContainerSecurity) c; + sc.toggleSetting( this.Value, player ); + } + else if( this.Name.equals( "PriorityHost.Priority" ) && c instanceof ContainerPriority ) + { + ContainerPriority pc = (ContainerPriority) c; + pc.setPriority( Integer.parseInt( this.Value ), player ); + } + else if( this.Name.equals( "LevelEmitter.Value" ) && c instanceof ContainerLevelEmitter ) + { + ContainerLevelEmitter lvc = (ContainerLevelEmitter) c; + lvc.setLevel( Long.parseLong( this.Value ), player ); + } + else if( this.Name.startsWith( "PatternTerminal." ) && c instanceof ContainerPatternTerm ) + { + ContainerPatternTerm cpt = (ContainerPatternTerm) c; + if( this.Name.equals( "PatternTerminal.CraftMode" ) ) + { + cpt.ct.setCraftingRecipe( this.Value.equals( "1" ) ); + } + else if( this.Name.equals( "PatternTerminal.Encode" ) ) + { + cpt.encode(); + } + else if( this.Name.equals( "PatternTerminal.Clear" ) ) + { + cpt.clear(); + } + } + else if( this.Name.startsWith( "StorageBus." ) && c instanceof ContainerStorageBus ) + { + ContainerStorageBus ccw = (ContainerStorageBus) c; + if( this.Name.equals( "StorageBus.Action" ) ) + { + if( this.Value.equals( "Partition" ) ) + { + ccw.partition(); + } + else if( this.Value.equals( "Clear" ) ) + { + ccw.clear(); + } + } + } + else if( this.Name.startsWith( "CellWorkbench." ) && c instanceof ContainerCellWorkbench ) + { + ContainerCellWorkbench ccw = (ContainerCellWorkbench) c; + if( this.Name.equals( "CellWorkbench.Action" ) ) + { + if( this.Value.equals( "CopyMode" ) ) + { + ccw.nextCopyMode(); + } + else if( this.Value.equals( "Partition" ) ) + { + ccw.partition(); + } + else if( this.Value.equals( "Clear" ) ) + { + ccw.clear(); + } + } + else if( this.Name.equals( "CellWorkbench.Fuzzy" ) ) + { + ccw.setFuzzy( FuzzyMode.valueOf( this.Value ) ); + } + } + else if( c instanceof ContainerNetworkTool ) + { + if( this.Name.equals( "NetworkTool" ) && this.Value.equals( "Toggle" ) ) + { + ( (ContainerNetworkTool) c ).toggleFacadeMode(); + } + } + else if( c instanceof IConfigurableObject ) + { + IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); + + for( Settings e : cm.getSettings() ) + { + if( e.name().equals( this.Name ) ) + { + Enum def = cm.getSetting( e ); + + try + { + cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); + } + catch( IllegalArgumentException err ) + { + // :P + } + + break; + } + } + } + } + + @Override + public void clientPacketData( INetworkInfo network, AppEngPacket packet, EntityPlayer player ) + { + Container c = player.openContainer; + + if( this.Name.equals( "CustomName" ) && c instanceof AEBaseContainer ) + { + ( (AEBaseContainer) c ).customName = this.Value; + } + else if( this.Name.startsWith( "SyncDat." ) ) + { + ( (AEBaseContainer) c ).stringSync( Integer.parseInt( this.Name.substring( 8 ) ), this.Value ); + } + else if( this.Name.equals( "CraftingStatus" ) && this.Value.equals( "Clear" ) ) + { + GuiScreen gs = Minecraft.getMinecraft().currentScreen; + if( gs instanceof GuiCraftingCPU ) + ( (GuiCraftingCPU) gs ).clearItems(); + } + else if( c instanceof IConfigurableObject ) + { + IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); + + for( Settings e : cm.getSettings() ) + { + if( e.name().equals( this.Name ) ) + { + Enum def = cm.getSetting( e ); + + try + { + cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); + } + catch( IllegalArgumentException err ) + { + // :P + } + + break; + } + } + } + } } diff --git a/src/main/java/appeng/crafting/CraftBranchFailure.java b/src/main/java/appeng/crafting/CraftBranchFailure.java index cd4ce9d61..fcd517fa3 100644 --- a/src/main/java/appeng/crafting/CraftBranchFailure.java +++ b/src/main/java/appeng/crafting/CraftBranchFailure.java @@ -18,8 +18,10 @@ package appeng.crafting; + import appeng.api.storage.data.IAEItemStack; + public class CraftBranchFailure extends Exception { @@ -27,7 +29,8 @@ public class CraftBranchFailure extends Exception final IAEItemStack missing; - public CraftBranchFailure(IAEItemStack what, long howMany) { + public CraftBranchFailure( IAEItemStack what, long howMany ) + { super( "Failed: " + what.getItem().getUnlocalizedName() + " x " + howMany ); this.missing = what.copy(); this.missing.setStackSize( howMany ); diff --git a/src/main/java/appeng/crafting/CraftingCalculationFailure.java b/src/main/java/appeng/crafting/CraftingCalculationFailure.java index 61066ff6d..fbb66eaca 100644 --- a/src/main/java/appeng/crafting/CraftingCalculationFailure.java +++ b/src/main/java/appeng/crafting/CraftingCalculationFailure.java @@ -18,8 +18,10 @@ package appeng.crafting; + import appeng.api.storage.data.IAEItemStack; + public class CraftingCalculationFailure extends RuntimeException { @@ -27,7 +29,8 @@ public class CraftingCalculationFailure extends RuntimeException final IAEItemStack missing; - public CraftingCalculationFailure(IAEItemStack what, long howMany) { + public CraftingCalculationFailure( IAEItemStack what, long howMany ) + { super( "this should have been caught!" ); this.missing = what.copy(); this.missing.setStackSize( howMany ); diff --git a/src/main/java/appeng/crafting/CraftingJob.java b/src/main/java/appeng/crafting/CraftingJob.java index 36b629ba0..a8f6a89bc 100644 --- a/src/main/java/appeng/crafting/CraftingJob.java +++ b/src/main/java/appeng/crafting/CraftingJob.java @@ -42,33 +42,32 @@ import appeng.api.storage.data.IItemList; import appeng.core.AELog; import appeng.hooks.TickHandler; + public class CraftingJob implements Runnable, ICraftingJob { - IAEItemStack output; - final IItemList storage; - final HashSet prophecies; - - boolean simulate = false; final MECraftingInventory original; - - MECraftingInventory availableCheck; + final World world; + final IItemList crafting = AEApi.instance().storage().createItemList(); + final IItemList missing = AEApi.instance().storage().createItemList(); + final HashMap opsAndMultiplier = new HashMap(); + private final Object monitor = new Object(); + private final Stopwatch watch = Stopwatch.createUnstarted(); public CraftingTreeNode tree; + IAEItemStack output; + boolean simulate = false; + MECraftingInventory availableCheck; + long bytes = 0; private BaseActionSource actionSrc; private ICraftingCallback callback; + private boolean running = false; + private boolean done = false; + private int time = 5; + private int incTime = Integer.MAX_VALUE; - long bytes = 0; - final World world; - - @Override - public IAEItemStack getOutput() - { - return this.output; - } - - public CraftingJob(World w, NBTTagCompound data) + public CraftingJob( World w, NBTTagCompound data ) { this.world = this.wrapWorld( w ); this.storage = AEApi.instance().storage().createItemList(); @@ -77,17 +76,12 @@ public class CraftingJob implements Runnable, ICraftingJob this.availableCheck = null; } - public void refund(IAEItemStack o) + private World wrapWorld( World w ) { - this.availableCheck.injectItems( o, Actionable.MODULATE, this.actionSrc ); + return w; } - public IAEItemStack checkUse(IAEItemStack available) - { - return this.availableCheck.extractItems( available, Actionable.MODULATE, this.actionSrc ); - } - - public CraftingJob(World w, IGrid grid, BaseActionSource actionSrc, IAEItemStack what, ICraftingCallback callback) + public CraftingJob( World w, IGrid grid, BaseActionSource actionSrc, IAEItemStack what, ICraftingCallback callback ) { this.world = this.wrapWorld( w ); this.output = what.copy(); @@ -104,33 +98,29 @@ public class CraftingJob implements Runnable, ICraftingJob this.availableCheck = null; } - private World wrapWorld(World w) - { - return w; - } - - private CraftingTreeNode getCraftingTree(ICraftingGrid cc, IAEItemStack what) + private CraftingTreeNode getCraftingTree( ICraftingGrid cc, IAEItemStack what ) { return new CraftingTreeNode( cc, this, what, null, -1, 0 ); } - @Override - public long getByteTotal() + public void refund( IAEItemStack o ) { - return this.bytes; + this.availableCheck.injectItems( o, Actionable.MODULATE, this.actionSrc ); } - public void writeToNBT(NBTTagCompound out) + public IAEItemStack checkUse( IAEItemStack available ) + { + return this.availableCheck.extractItems( available, Actionable.MODULATE, this.actionSrc ); + } + + public void writeToNBT( NBTTagCompound out ) { } - final IItemList crafting = AEApi.instance().storage().createItemList(); - final IItemList missing = AEApi.instance().storage().createItemList(); - - public void addTask(IAEItemStack what, long crafts, ICraftingPatternDetails details, int depth) + public void addTask( IAEItemStack what, long crafts, ICraftingPatternDetails details, int depth ) { - if ( crafts > 0 ) + if( crafts > 0 ) { what = what.copy(); what.setStackSize( what.getStackSize() * crafts ); @@ -138,21 +128,12 @@ public class CraftingJob implements Runnable, ICraftingJob } } - public void addMissing(IAEItemStack what) + public void addMissing( IAEItemStack what ) { what = what.copy(); this.missing.add( what ); } - static class TwoIntegers - { - - public final long perOp = 0; - public final long times = 0; - } - - final HashMap opsAndMultiplier = new HashMap(); - @Override public void run() { @@ -172,17 +153,17 @@ public class CraftingJob implements Runnable, ICraftingJob this.tree.request( craftingInventory, this.output.getStackSize(), this.actionSrc ); this.tree.dive( this ); - for (String s : this.opsAndMultiplier.keySet()) + for( String s : this.opsAndMultiplier.keySet() ) { TwoIntegers ti = this.opsAndMultiplier.get( s ); - AELog.crafting( s + " * " + ti.times + " = " + (ti.perOp * ti.times) ); + AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) ); } AELog.crafting( "------------- " + this.bytes + "b real" + timer.elapsed( TimeUnit.MILLISECONDS ) + "ms" ); // if ( mode == Actionable.MODULATE ) // craftingInventory.moveItemsToStorage( storage ); } - catch (CraftBranchFailure e) + catch( CraftBranchFailure e ) { this.simulate = true; @@ -198,34 +179,34 @@ public class CraftingJob implements Runnable, ICraftingJob this.tree.request( craftingInventory, this.output.getStackSize(), this.actionSrc ); this.tree.dive( this ); - for (String s : this.opsAndMultiplier.keySet()) + for( String s : this.opsAndMultiplier.keySet() ) { TwoIntegers ti = this.opsAndMultiplier.get( s ); - AELog.crafting( s + " * " + ti.times + " = " + (ti.perOp * ti.times) ); + AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) ); } AELog.crafting( "------------- " + this.bytes + "b simulate" + timer.elapsed( TimeUnit.MILLISECONDS ) + "ms" ); } - catch (CraftBranchFailure e1) + catch( CraftBranchFailure e1 ) { AELog.error( e1 ); } - catch (CraftingCalculationFailure f) + catch( CraftingCalculationFailure f ) { AELog.error( f ); } - catch (InterruptedException e1) + catch( InterruptedException e1 ) { AELog.crafting( "Crafting calculation canceled." ); this.finish(); return; } } - catch (CraftingCalculationFailure f) + catch( CraftingCalculationFailure f ) { AELog.error( f ); } - catch (InterruptedException e1) + catch( InterruptedException e1 ) { AELog.crafting( "Crafting calculation canceled." ); this.finish(); @@ -234,24 +215,57 @@ public class CraftingJob implements Runnable, ICraftingJob this.log( "crafting job now done" ); } - catch (Throwable t) + catch( Throwable t ) { this.finish(); throw new RuntimeException( t ); } this.finish(); + } + public void handlePausing() throws InterruptedException + { + if( this.incTime > 100 ) + { + this.incTime = 0; + + synchronized( this.monitor ) + { + if( this.watch.elapsed( TimeUnit.MICROSECONDS ) > this.time ) + { + this.running = false; + this.watch.stop(); + this.monitor.notify(); + } + + if( !this.running ) + { + this.log( "crafting job will now sleep" ); + + while( !this.running ) + { + this.monitor.wait(); + } + + this.log( "crafting job now active" ); + } + } + + if( Thread.interrupted() ) + throw new InterruptedException(); + } + this.incTime++; } public void finish() { - if ( this.callback != null ) + if( this.callback != null ) this.callback.calculationComplete( this ); this.availableCheck = null; - synchronized (this.monitor) + synchronized( this.monitor ) { this.running = false; this.done = true; @@ -259,12 +273,36 @@ public class CraftingJob implements Runnable, ICraftingJob } } + private void log( String string ) + { + // AELog.crafting( string ); + } + @Override public boolean isSimulation() { return this.simulate; } + @Override + public long getByteTotal() + { + return this.bytes; + } + + @Override + public void populatePlan( IItemList plan ) + { + if( this.tree != null ) + this.tree.getPlan( plan ); + } + + @Override + public IAEItemStack getOutput() + { + return this.output; + } + public boolean isDone() { return this.done; @@ -275,25 +313,20 @@ public class CraftingJob implements Runnable, ICraftingJob return this.world; } - private boolean running = false; - private boolean done = false; - private final Object monitor = new Object(); - private final Stopwatch watch = Stopwatch.createUnstarted(); - private int time = 5; - /** * returns true if this needs more simulation. * * @param milli milliseconds of simulation + * * @return true if this needs more simulation */ - public boolean simulateFor(int milli) + public boolean simulateFor( int milli ) { this.time = milli; - synchronized (this.monitor) + synchronized( this.monitor ) { - if ( this.done ) + if( this.done ) return false; this.watch.reset(); @@ -304,13 +337,13 @@ public class CraftingJob implements Runnable, ICraftingJob this.monitor.notify(); - while (this.running) + while( this.running ) { try { this.monitor.wait(); } - catch (InterruptedException ignored) + catch( InterruptedException ignored ) { } } @@ -321,57 +354,15 @@ public class CraftingJob implements Runnable, ICraftingJob return true; } - private int incTime = Integer.MAX_VALUE; - - public void handlePausing() throws InterruptedException - { - if ( this.incTime > 100 ) - { - this.incTime = 0; - - synchronized (this.monitor) - { - if ( this.watch.elapsed( TimeUnit.MICROSECONDS ) > this.time ) - { - this.running = false; - this.watch.stop(); - this.monitor.notify(); - } - - if ( !this.running ) - { - this.log( "crafting job will now sleep" ); - - while (!this.running) - { - this.monitor.wait(); - } - - this.log( "crafting job now active" ); - } - } - - if ( Thread.interrupted() ) - throw new InterruptedException(); - } - this.incTime++; - } - - private void log(String string) - { - // AELog.crafting( string ); - } - - public void addBytes(long crafts) + public void addBytes( long crafts ) { this.bytes += crafts; } - @Override - public void populatePlan(IItemList plan) + static class TwoIntegers { - if ( this.tree != null ) - this.tree.getPlan( plan ); - } + public final long perOp = 0; + public final long times = 0; + } } diff --git a/src/main/java/appeng/crafting/CraftingLink.java b/src/main/java/appeng/crafting/CraftingLink.java index 1c5608e7f..e677cfb6a 100644 --- a/src/main/java/appeng/crafting/CraftingLink.java +++ b/src/main/java/appeng/crafting/CraftingLink.java @@ -18,6 +18,7 @@ package appeng.crafting; + import net.minecraft.nbt.NBTTagCompound; import appeng.api.config.Actionable; @@ -26,40 +27,40 @@ import appeng.api.networking.crafting.ICraftingLink; import appeng.api.networking.crafting.ICraftingRequester; import appeng.api.storage.data.IAEItemStack; + public class CraftingLink implements ICraftingLink { - boolean canceled = false; - boolean done = false; - - CraftingLinkNexus tie; - final ICraftingRequester req; final ICraftingCPU cpu; - final String CraftID; final boolean standalone; + boolean canceled = false; + boolean done = false; + CraftingLinkNexus tie; - public CraftingLink(NBTTagCompound data, ICraftingRequester req) { + public CraftingLink( NBTTagCompound data, ICraftingRequester req ) + { this.CraftID = data.getString( "CraftID" ); this.canceled = data.getBoolean( "canceled" ); this.done = data.getBoolean( "done" ); this.standalone = data.getBoolean( "standalone" ); - if ( !data.hasKey( "req" ) || !data.getBoolean( "req" ) ) + if( !data.hasKey( "req" ) || !data.getBoolean( "req" ) ) throw new RuntimeException( "Invalid Crafting Link for Object" ); this.req = req; this.cpu = null; } - public CraftingLink(NBTTagCompound data, ICraftingCPU cpu) { + public CraftingLink( NBTTagCompound data, ICraftingCPU cpu ) + { this.CraftID = data.getString( "CraftID" ); this.canceled = data.getBoolean( "canceled" ); this.done = data.getBoolean( "done" ); this.standalone = data.getBoolean( "standalone" ); - if ( !data.hasKey( "req" ) || data.getBoolean( "req" ) ) + if( !data.hasKey( "req" ) || data.getBoolean( "req" ) ) throw new RuntimeException( "Invalid Crafting Link for Object" ); this.cpu = cpu; @@ -69,13 +70,13 @@ public class CraftingLink implements ICraftingLink @Override public boolean isCanceled() { - if ( this.canceled ) + if( this.canceled ) return true; - if ( this.done ) + if( this.done ) return false; - if ( this.tie == null ) + if( this.tie == null ) return false; return this.tie.isCanceled(); @@ -84,13 +85,13 @@ public class CraftingLink implements ICraftingLink @Override public boolean isDone() { - if ( this.done ) + if( this.done ) return true; - if ( this.canceled ) + if( this.canceled ) return false; - if ( this.tie == null ) + if( this.tie == null ) return false; return this.tie.isDone(); @@ -99,60 +100,60 @@ public class CraftingLink implements ICraftingLink @Override public void cancel() { - if ( this.done ) + if( this.done ) return; this.canceled = true; - if ( this.tie != null ) + if( this.tie != null ) this.tie.cancel(); this.tie = null; } - @Override - public void writeToNBT(NBTTagCompound tag) - { - tag.setString( "CraftID", this.CraftID ); - tag.setBoolean( "canceled", this.canceled ); - tag.setBoolean( "done", this.done ); - tag.setBoolean( "standalone", this.standalone ); - tag.setBoolean( "req", this.req != null ); - } - - public void setNexus(CraftingLinkNexus n) - { - if ( this.tie != null ) - this.tie.remove( this ); - - if ( this.canceled && n != null ) - { - n.cancel(); - this.tie = null; - return; - } - - this.tie = n; - - if ( n != null ) - n.add( this ); - } - - @Override - public String getCraftingID() - { - return this.CraftID; - } - @Override public boolean isStandalone() { return this.standalone; } - public IAEItemStack injectItems(IAEItemStack input, Actionable mode) + @Override + public void writeToNBT( NBTTagCompound tag ) { - if ( this.tie == null || this.tie.req == null || this.tie.req.req == null ) + tag.setString( "CraftID", this.CraftID ); + tag.setBoolean( "canceled", this.canceled ); + tag.setBoolean( "done", this.done ); + tag.setBoolean( "standalone", this.standalone ); + tag.setBoolean( "req", this.req != null ); + } + + @Override + public String getCraftingID() + { + return this.CraftID; + } + + public void setNexus( CraftingLinkNexus n ) + { + if( this.tie != null ) + this.tie.remove( this ); + + if( this.canceled && n != null ) + { + n.cancel(); + this.tie = null; + return; + } + + this.tie = n; + + if( n != null ) + n.add( this ); + } + + public IAEItemStack injectItems( IAEItemStack input, Actionable mode ) + { + if( this.tie == null || this.tie.req == null || this.tie.req.req == null ) return input; return this.tie.req.req.injectCraftedItems( this.tie.req, input, mode ); @@ -160,7 +161,7 @@ public class CraftingLink implements ICraftingLink public void markDone() { - if ( this.tie != null ) + if( this.tie != null ) this.tie.markDone(); } } diff --git a/src/main/java/appeng/crafting/CraftingLinkNexus.java b/src/main/java/appeng/crafting/CraftingLinkNexus.java index a19cda320..b88b96874 100644 --- a/src/main/java/appeng/crafting/CraftingLinkNexus.java +++ b/src/main/java/appeng/crafting/CraftingLinkNexus.java @@ -18,46 +18,46 @@ package appeng.crafting; + import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.me.cache.CraftingGridCache; + public class CraftingLinkNexus { - public CraftingLinkNexus(String craftID) { - this.CraftID = craftID; - } - public final String CraftID; - boolean canceled = false; boolean done = false; - int tickOfDeath = 0; - CraftingLink req; CraftingLink cpu; - public boolean isDead(IGrid g, CraftingGridCache craftingGridCache) + public CraftingLinkNexus( String craftID ) { - if ( this.canceled || this.done ) + this.CraftID = craftID; + } + + public boolean isDead( IGrid g, CraftingGridCache craftingGridCache ) + { + if( this.canceled || this.done ) return true; - if ( this.req == null || this.cpu == null ) + if( this.req == null || this.cpu == null ) this.tickOfDeath++; else { boolean hasCpu = craftingGridCache.hasCpu( this.cpu.cpu ); boolean hasMachine = this.req.req.getActionableNode().getGrid() == g; - if ( hasCpu && hasMachine ) + if( hasCpu && hasMachine ) this.tickOfDeath = 0; else this.tickOfDeath += 60; } - if ( this.tickOfDeath > 60 ) + if( this.tickOfDeath > 60 ) { this.cancel(); return true; @@ -66,19 +66,34 @@ public class CraftingLinkNexus return false; } - public void remove(CraftingLink craftingLink) + public void cancel() { - if ( this.req == craftingLink ) + this.canceled = true; + + if( this.req != null ) + { + this.req.canceled = true; + if( this.req.req != null ) + this.req.req.jobStateChange( this.req ); + } + + if( this.cpu != null ) + this.cpu.canceled = true; + } + + public void remove( CraftingLink craftingLink ) + { + if( this.req == craftingLink ) this.req = null; - else if ( this.cpu == craftingLink ) + else if( this.cpu == craftingLink ) this.cpu = null; } - public void add(CraftingLink craftingLink) + public void add( CraftingLink craftingLink ) { - if ( craftingLink.cpu != null ) + if( craftingLink.cpu != null ) this.cpu = craftingLink; - else if ( craftingLink.req != null ) + else if( craftingLink.req != null ) this.req = craftingLink; } @@ -96,44 +111,28 @@ public class CraftingLinkNexus { this.done = true; - if ( this.req != null ) + if( this.req != null ) { this.req.done = true; - if ( this.req.req != null ) + if( this.req.req != null ) this.req.req.jobStateChange( this.req ); } - if ( this.cpu != null ) + if( this.cpu != null ) this.cpu.done = true; } - public void cancel() - { - this.canceled = true; - - if ( this.req != null ) - { - this.req.canceled = true; - if ( this.req.req != null ) - this.req.req.jobStateChange( this.req ); - } - - if ( this.cpu != null ) - this.cpu.canceled = true; - } - - public boolean isMachine(IGridHost machine) + public boolean isMachine( IGridHost machine ) { return this.req == machine; } public void removeNode() { - if ( this.req != null ) + if( this.req != null ) this.req.setNexus( null ); this.req = null; this.tickOfDeath = 0; } - } diff --git a/src/main/java/appeng/crafting/CraftingTreeNode.java b/src/main/java/appeng/crafting/CraftingTreeNode.java index f1fc10cc0..5d92935c8 100644 --- a/src/main/java/appeng/crafting/CraftingTreeNode.java +++ b/src/main/java/appeng/crafting/CraftingTreeNode.java @@ -35,36 +35,31 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.me.cluster.implementations.CraftingCPUCluster; + public class CraftingTreeNode { + // what slot! + final int slot; + final CraftingJob job; + final IItemList used = AEApi.instance().storage().createItemList(); // parent node. private final CraftingTreeProcess parent; private final World world; - - // what slot! - final int slot; - int bytes = 0; - // what item is this? private final IAEItemStack what; - // what are the crafting patterns for this? private final ArrayList nodes = new ArrayList(); - + int bytes = 0; boolean canEmit = false; boolean cannotUse = false; - long missing = 0; long howManyEmitted = 0; - - final CraftingJob job; - final IItemList used = AEApi.instance().storage().createItemList(); boolean exhausted = false; boolean sim; - public CraftingTreeNode(ICraftingGrid cc, CraftingJob job, IAEItemStack wat, CraftingTreeProcess par, int slot, int depth) + public CraftingTreeNode( ICraftingGrid cc, CraftingJob job, IAEItemStack wat, CraftingTreeProcess par, int slot, int depth ) { this.what = wat; this.parent = par; @@ -74,66 +69,58 @@ public class CraftingTreeNode this.sim = false; this.canEmit = cc.canEmitFor( this.what ); - if ( this.canEmit ) + if( this.canEmit ) return; // if you can emit for something, you can't make it with patterns. - for (ICraftingPatternDetails details : cc.getCraftingFor( this.what, this.parent == null ? null : this.parent.details, slot, this.world ))// in - // order. + for( ICraftingPatternDetails details : cc.getCraftingFor( this.what, this.parent == null ? null : this.parent.details, slot, this.world ) )// in + // order. { - if ( this.parent == null || this.parent.notRecursive( details ) ) + if( this.parent == null || this.parent.notRecursive( details ) ) this.nodes.add( new CraftingTreeProcess( cc, job, details, this, depth + 1 ) ); } - } - public IAEItemStack getStack(long size) - { - IAEItemStack is = this.what.copy(); - is.setStackSize( size ); - return is; - } - - boolean notRecursive(ICraftingPatternDetails details) + boolean notRecursive( ICraftingPatternDetails details ) { IAEItemStack[] o = details.getCondensedOutputs(); - for (IAEItemStack i : o) - if ( i.equals( this.what ) ) + for( IAEItemStack i : o ) + if( i.equals( this.what ) ) return false; o = details.getCondensedInputs(); - for (IAEItemStack i : o) - if ( i.equals( this.what ) ) + for( IAEItemStack i : o ) + if( i.equals( this.what ) ) return false; - if ( this.parent == null ) + if( this.parent == null ) return true; return this.parent.notRecursive( details ); } - public IAEItemStack request(MECraftingInventory inv, long l, BaseActionSource src) throws CraftBranchFailure, InterruptedException + public IAEItemStack request( MECraftingInventory inv, long l, BaseActionSource src ) throws CraftBranchFailure, InterruptedException { this.job.handlePausing(); List thingsUsed = new LinkedList(); this.what.setStackSize( l ); - if ( this.slot >= 0 && this.parent != null && this.parent.details.isCraftable() ) + if( this.slot >= 0 && this.parent != null && this.parent.details.isCraftable() ) { - for (IAEItemStack fuzz : inv.getItemList().findFuzzy( this.what, FuzzyMode.IGNORE_ALL )) + for( IAEItemStack fuzz : inv.getItemList().findFuzzy( this.what, FuzzyMode.IGNORE_ALL ) ) { - if ( this.parent.details.isValidItemForSlot( this.slot, fuzz.getItemStack(), this.world ) ) + if( this.parent.details.isValidItemForSlot( this.slot, fuzz.getItemStack(), this.world ) ) { fuzz = fuzz.copy(); fuzz.setStackSize( l ); IAEItemStack available = inv.extractItems( fuzz, Actionable.MODULATE, src ); - if ( available != null ) + if( available != null ) { - if ( !this.exhausted ) + if( !this.exhausted ) { IAEItemStack is = this.job.checkUse( available ); - if ( is != null ) + if( is != null ) { thingsUsed.add( is.copy() ); this.used.add( is ); @@ -143,7 +130,7 @@ public class CraftingTreeNode this.bytes += available.getStackSize(); l -= available.getStackSize(); - if ( l == 0 ) + if( l == 0 ) return available; } } @@ -153,12 +140,12 @@ public class CraftingTreeNode { IAEItemStack available = inv.extractItems( this.what, Actionable.MODULATE, src ); - if ( available != null ) + if( available != null ) { - if ( !this.exhausted ) + if( !this.exhausted ) { IAEItemStack is = this.job.checkUse( available ); - if ( is != null ) + if( is != null ) { thingsUsed.add( is.copy() ); this.used.add( is ); @@ -168,12 +155,12 @@ public class CraftingTreeNode this.bytes += available.getStackSize(); l -= available.getStackSize(); - if ( l == 0 ) + if( l == 0 ) return available; } } - if ( this.canEmit ) + if( this.canEmit ) { IAEItemStack wat = this.what.copy(); wat.setStackSize( l ); @@ -186,11 +173,11 @@ public class CraftingTreeNode this.exhausted = true; - if ( this.nodes.size() == 1 ) + if( this.nodes.size() == 1 ) { CraftingTreeProcess pro = this.nodes.get( 0 ); - while (pro.possible && l > 0) + while( pro.possible && l > 0 ) { IAEItemStack madeWhat = pro.getAmountCrafted( this.what ); @@ -199,25 +186,25 @@ public class CraftingTreeNode madeWhat.setStackSize( l ); IAEItemStack available = inv.extractItems( madeWhat, Actionable.MODULATE, src ); - if ( available != null ) + if( available != null ) { this.bytes += available.getStackSize(); l -= available.getStackSize(); - if ( l <= 0 ) + if( l <= 0 ) return available; } else pro.possible = false; // ;P } } - else if ( this.nodes.size() > 1 ) + else if( this.nodes.size() > 1 ) { - for (CraftingTreeProcess pro : this.nodes) + for( CraftingTreeProcess pro : this.nodes ) { try { - while (pro.possible && l > 0) + while( pro.possible && l > 0 ) { MECraftingInventory subInv = new MECraftingInventory( inv, true, true, true ); pro.request( subInv, 1, src ); @@ -225,29 +212,29 @@ public class CraftingTreeNode this.what.setStackSize( l ); IAEItemStack available = subInv.extractItems( this.what, Actionable.MODULATE, src ); - if ( available != null ) + if( available != null ) { - if ( !subInv.commit( src ) ) + if( !subInv.commit( src ) ) throw new CraftBranchFailure( this.what, l ); this.bytes += available.getStackSize(); l -= available.getStackSize(); - if ( l <= 0 ) + if( l <= 0 ) return available; } else pro.possible = false; // ;P } } - catch (CraftBranchFailure fail) + catch( CraftBranchFailure fail ) { pro.possible = true; } } } - if ( this.sim ) + if( this.sim ) { this.missing += l; this.bytes += l; @@ -256,7 +243,7 @@ public class CraftingTreeNode return rv; } - for (IAEItemStack o : thingsUsed) + for( IAEItemStack o : thingsUsed ) { this.job.refund( o.copy() ); o.setStackSize( -o.getStackSize() ); @@ -266,18 +253,25 @@ public class CraftingTreeNode throw new CraftBranchFailure( this.what, l ); } - public void dive(CraftingJob job) + public void dive( CraftingJob job ) { - if ( this.missing > 0 ) + if( this.missing > 0 ) job.addMissing( this.getStack( this.missing ) ); // missing = 0; job.addBytes( 8 + this.bytes ); - for (CraftingTreeProcess pro : this.nodes) + for( CraftingTreeProcess pro : this.nodes ) pro.dive( job ); } + public IAEItemStack getStack( long size ) + { + IAEItemStack is = this.what.copy(); + is.setStackSize( size ); + return is; + } + public void setSimulate() { this.sim = true; @@ -286,53 +280,53 @@ public class CraftingTreeNode this.used.resetStatus(); this.exhausted = false; - for (CraftingTreeProcess pro : this.nodes) + for( CraftingTreeProcess pro : this.nodes ) pro.setSimulate(); } - public void setJob(MECraftingInventory storage, CraftingCPUCluster craftingCPUCluster, BaseActionSource src) throws CraftBranchFailure + public void setJob( MECraftingInventory storage, CraftingCPUCluster craftingCPUCluster, BaseActionSource src ) throws CraftBranchFailure { - for (IAEItemStack i : this.used) + for( IAEItemStack i : this.used ) { IAEItemStack ex = storage.extractItems( i, Actionable.MODULATE, src ); - if ( ex == null || ex.getStackSize() != i.getStackSize() ) + if( ex == null || ex.getStackSize() != i.getStackSize() ) throw new CraftBranchFailure( i, i.getStackSize() ); craftingCPUCluster.addStorage( ex ); } - if ( this.howManyEmitted > 0 ) + if( this.howManyEmitted > 0 ) { IAEItemStack i = this.what.copy(); i.setStackSize( this.howManyEmitted ); craftingCPUCluster.addEmitable( i ); } - for (CraftingTreeProcess pro : this.nodes) + for( CraftingTreeProcess pro : this.nodes ) pro.setJob( storage, craftingCPUCluster, src ); } - public void getPlan(IItemList plan) + public void getPlan( IItemList plan ) { - if ( this.missing > 0 ) + if( this.missing > 0 ) { IAEItemStack o = this.what.copy(); o.setStackSize( this.missing ); plan.add( o ); } - if ( this.howManyEmitted > 0 ) + if( this.howManyEmitted > 0 ) { IAEItemStack i = this.what.copy(); i.setCountRequestable( this.howManyEmitted ); plan.addRequestable( i ); } - for (IAEItemStack i : this.used) + for( IAEItemStack i : this.used ) plan.add( i.copy() ); - for (CraftingTreeProcess pro : this.nodes) + for( CraftingTreeProcess pro : this.nodes ) pro.getPlan( plan ); } } diff --git a/src/main/java/appeng/crafting/CraftingTreeProcess.java b/src/main/java/appeng/crafting/CraftingTreeProcess.java index 5bc23f49e..e9d322570 100644 --- a/src/main/java/appeng/crafting/CraftingTreeProcess.java +++ b/src/main/java/appeng/crafting/CraftingTreeProcess.java @@ -41,88 +41,87 @@ import appeng.container.ContainerNull; import appeng.me.cluster.implementations.CraftingCPUCluster; import appeng.util.Platform; + public class CraftingTreeProcess { - World world; final CraftingTreeNode parent; final ICraftingPatternDetails details; final CraftingJob job; - + final Map nodes = new HashMap(); + final private int depth; + public boolean possible = true; + World world; long crafts = 0; boolean containerItems; boolean limitQty; boolean fullSimulation; - private long bytes = 0; - final private int depth; - final Map nodes = new HashMap(); - public boolean possible = true; - - public CraftingTreeProcess( ICraftingGrid cc, CraftingJob job, ICraftingPatternDetails details, CraftingTreeNode craftingTreeNode, int depth ) { + public CraftingTreeProcess( ICraftingGrid cc, CraftingJob job, ICraftingPatternDetails details, CraftingTreeNode craftingTreeNode, int depth ) + { this.parent = craftingTreeNode; this.details = details; this.job = job; this.depth = depth; World world = job.getWorld(); - if ( details.isCraftable() ) + if( details.isCraftable() ) { IAEItemStack[] list = details.getInputs(); InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); IAEItemStack[] is = details.getInputs(); - for (int x = 0; x < ic.getSizeInventory(); x++) + for( int x = 0; x < ic.getSizeInventory(); x++ ) ic.setInventorySlotContents( x, is[x] == null ? null : is[x].getItemStack() ); FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) world ), details.getOutput( ic, world ), ic ); - for (int x = 0; x < ic.getSizeInventory(); x++) + for( int x = 0; x < ic.getSizeInventory(); x++ ) { ItemStack g = ic.getStackInSlot( x ); - if ( g != null && g.stackSize > 1 ) + if( g != null && g.stackSize > 1 ) this.fullSimulation = true; } - for ( IAEItemStack part : details.getCondensedInputs() ) + for( IAEItemStack part : details.getCondensedInputs() ) { ItemStack g = part.getItemStack(); boolean isAnInput = false; - for ( IAEItemStack a : details.getCondensedOutputs() ) + for( IAEItemStack a : details.getCondensedOutputs() ) { - if ( g != null && a != null && a.equals( g ) ) + if( g != null && a != null && a.equals( g ) ) isAnInput = true; } - if ( isAnInput ) + if( isAnInput ) this.limitQty = true; - if ( g.getItem().hasContainerItem( g ) ) + if( g.getItem().hasContainerItem( g ) ) this.limitQty = this.containerItems = true; } boolean complicated = false; - if ( this.containerItems || complicated ) + if( this.containerItems || complicated ) { - for (int x = 0; x < list.length; x++) + for( int x = 0; x < list.length; x++ ) { IAEItemStack part = list[x]; - if ( part != null ) + if( part != null ) this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1 ), part.getStackSize() ); } } else { // this is minor different then below, this slot uses the pattern, but kinda fudges it. - for (IAEItemStack part : details.getCondensedInputs()) + for( IAEItemStack part : details.getCondensedInputs() ) { - for (int x = 0; x < list.length; x++) + for( int x = 0; x < list.length; x++ ) { IAEItemStack comparePart = list[x]; - if ( part != null && part.equals( comparePart ) ) + if( part != null && part.equals( comparePart ) ) { // use the first slot... this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1 ), part.getStackSize() ); @@ -134,75 +133,49 @@ public class CraftingTreeProcess } else { - for ( IAEItemStack part : details.getCondensedInputs() ) + for( IAEItemStack part : details.getCondensedInputs() ) { ItemStack g = part.getItemStack(); boolean isAnInput = false; - for (IAEItemStack a : details.getCondensedOutputs()) + for( IAEItemStack a : details.getCondensedOutputs() ) { - if ( g != null && a != null && a.equals( g ) ) + if( g != null && a != null && a.equals( g ) ) isAnInput = true; } - if ( isAnInput ) + if( isAnInput ) this.limitQty = true; } - for (IAEItemStack part : details.getCondensedInputs()) + for( IAEItemStack part : details.getCondensedInputs() ) { this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, -1, depth + 1 ), part.getStackSize() ); } } } - public boolean notRecursive(ICraftingPatternDetails details) + public boolean notRecursive( ICraftingPatternDetails details ) { return this.parent == null || this.parent.notRecursive( details ); } - long getTimes(long remaining, long stackSize) + long getTimes( long remaining, long stackSize ) { - if ( this.limitQty || this.fullSimulation ) + if( this.limitQty || this.fullSimulation ) return 1; - return (remaining / stackSize) + (remaining % stackSize != 0 ? 1 : 0); + return ( remaining / stackSize ) + ( remaining % stackSize != 0 ? 1 : 0 ); } - IAEItemStack getAmountCrafted(IAEItemStack what2) - { - for (IAEItemStack is : this.details.getCondensedOutputs()) - { - if ( is.equals( what2 ) ) - { - what2 = what2.copy(); - what2.setStackSize( is.getStackSize() ); - return what2; - } - } - - // more fuzzy! - for (IAEItemStack is : this.details.getCondensedOutputs()) - { - if ( is.getItem() == what2.getItem() && (is.getItem().isDamageable() || is.getItemDamage() == what2.getItemDamage()) ) - { - what2 = is.copy(); - what2.setStackSize( is.getStackSize() ); - return what2; - } - } - - throw new RuntimeException( "Crafting Tree construction failed." ); - } - - public void request(MECraftingInventory inv, long i, BaseActionSource src) throws CraftBranchFailure, InterruptedException + public void request( MECraftingInventory inv, long i, BaseActionSource src ) throws CraftBranchFailure, InterruptedException { this.job.handlePausing(); - if ( this.fullSimulation ) + if( this.fullSimulation ) { InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for (Entry entry : this.nodes.entrySet()) + for( Entry entry : this.nodes.entrySet() ) { IAEItemStack item = entry.getKey().getStack( entry.getValue() ); IAEItemStack stack = entry.getKey().request( inv, item.getStackSize(), src ); @@ -212,13 +185,13 @@ public class CraftingTreeProcess FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.world ), this.details.getOutput( ic, this.world ), ic ); - for (int x = 0; x < ic.getSizeInventory(); x++) + for( int x = 0; x < ic.getSizeInventory(); x++ ) { ItemStack is = ic.getStackInSlot( x ); is = Platform.getContainerItem( is ); IAEItemStack o = AEApi.instance().storage().createItemStack( is ); - if ( o != null ) + if( o != null ) { this.bytes++; inv.injectItems( o, Actionable.MODULATE, src ); @@ -228,16 +201,16 @@ public class CraftingTreeProcess else { // request and remove inputs... - for (Entry entry : this.nodes.entrySet()) + for( Entry entry : this.nodes.entrySet() ) { IAEItemStack item = entry.getKey().getStack( entry.getValue() ); IAEItemStack stack = entry.getKey().request( inv, item.getStackSize() * i, src ); - if ( this.containerItems ) + if( this.containerItems ) { ItemStack is = Platform.getContainerItem( stack.getItemStack() ); IAEItemStack o = AEApi.instance().storage().createItemStack( is ); - if ( o != null ) + if( o != null ) { this.bytes++; inv.injectItems( o, Actionable.MODULATE, src ); @@ -249,7 +222,7 @@ public class CraftingTreeProcess // assume its possible. // add crafting results.. - for (IAEItemStack out : this.details.getCondensedOutputs()) + for( IAEItemStack out : this.details.getCondensedOutputs() ) { IAEItemStack o = out.copy(); o.setStackSize( o.getStackSize() * i ); @@ -259,42 +232,68 @@ public class CraftingTreeProcess this.crafts += i; } - public void dive(CraftingJob job) + public void dive( CraftingJob job ) { job.addTask( this.getAmountCrafted( this.parent.getStack( 1 ) ), this.crafts, this.details, this.depth ); - for (CraftingTreeNode pro : this.nodes.keySet()) + for( CraftingTreeNode pro : this.nodes.keySet() ) pro.dive( job ); job.addBytes( 8 + this.crafts + this.bytes ); } + IAEItemStack getAmountCrafted( IAEItemStack what2 ) + { + for( IAEItemStack is : this.details.getCondensedOutputs() ) + { + if( is.equals( what2 ) ) + { + what2 = what2.copy(); + what2.setStackSize( is.getStackSize() ); + return what2; + } + } + + // more fuzzy! + for( IAEItemStack is : this.details.getCondensedOutputs() ) + { + if( is.getItem() == what2.getItem() && ( is.getItem().isDamageable() || is.getItemDamage() == what2.getItemDamage() ) ) + { + what2 = is.copy(); + what2.setStackSize( is.getStackSize() ); + return what2; + } + } + + throw new RuntimeException( "Crafting Tree construction failed." ); + } + public void setSimulate() { this.crafts = 0; this.bytes = 0; - for (CraftingTreeNode pro : this.nodes.keySet()) + for( CraftingTreeNode pro : this.nodes.keySet() ) pro.setSimulate(); } - public void setJob(MECraftingInventory storage, CraftingCPUCluster craftingCPUCluster, BaseActionSource src) throws CraftBranchFailure + public void setJob( MECraftingInventory storage, CraftingCPUCluster craftingCPUCluster, BaseActionSource src ) throws CraftBranchFailure { craftingCPUCluster.addCrafting( this.details, this.crafts ); - for (CraftingTreeNode pro : this.nodes.keySet()) + for( CraftingTreeNode pro : this.nodes.keySet() ) pro.setJob( storage, craftingCPUCluster, src ); } - public void getPlan(IItemList plan) + public void getPlan( IItemList plan ) { - for (IAEItemStack i : this.details.getOutputs()) + for( IAEItemStack i : this.details.getOutputs() ) { i = i.copy(); i.setCountRequestable( i.getStackSize() * this.crafts ); plan.addRequestable( i ); } - for (CraftingTreeNode pro : this.nodes.keySet()) + for( CraftingTreeNode pro : this.nodes.keySet() ) pro.getPlan( plan ); } } diff --git a/src/main/java/appeng/crafting/CraftingWatcher.java b/src/main/java/appeng/crafting/CraftingWatcher.java index 517568c62..9e8f1a8ad 100644 --- a/src/main/java/appeng/crafting/CraftingWatcher.java +++ b/src/main/java/appeng/crafting/CraftingWatcher.java @@ -18,6 +18,7 @@ package appeng.crafting; + import java.util.Collection; import java.util.HashSet; import java.util.Iterator; @@ -27,12 +28,134 @@ import appeng.api.networking.crafting.ICraftingWatcherHost; import appeng.api.storage.data.IAEStack; import appeng.me.cache.CraftingGridCache; + /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ public class CraftingWatcher implements ICraftingWatcher { + final CraftingGridCache gsc; + final ICraftingWatcherHost host; + final HashSet myInterests = new HashSet(); + + public CraftingWatcher( CraftingGridCache cache, ICraftingWatcherHost host ) + { + this.gsc = cache; + this.host = host; + } + + public ICraftingWatcherHost getHost() + { + return this.host; + } + + @Override + public int size() + { + return this.myInterests.size(); + } + + @Override + public boolean isEmpty() + { + return this.myInterests.isEmpty(); + } + + @Override + public boolean contains( Object o ) + { + return this.myInterests.contains( o ); + } + + @Override + public Iterator iterator() + { + return new ItemWatcherIterator( this, this.myInterests.iterator() ); + } + + @Override + public Object[] toArray() + { + return this.myInterests.toArray(); + } + + @Override + public T[] toArray( T[] a ) + { + return this.myInterests.toArray( a ); + } + + @Override + public boolean add( IAEStack e ) + { + if( this.myInterests.contains( e ) ) + return false; + + return this.myInterests.add( e.copy() ) && this.gsc.interestManager.put( e, this ); + } + + @Override + public boolean remove( Object o ) + { + return this.myInterests.remove( o ) && this.gsc.interestManager.remove( (IAEStack) o, this ); + } + + @Override + public boolean containsAll( Collection c ) + { + return this.myInterests.containsAll( c ); + } + + @Override + public boolean addAll( Collection c ) + { + boolean didChange = false; + + for( IAEStack o : c ) + didChange = this.add( o ) || didChange; + + return didChange; + } + + @Override + public boolean removeAll( Collection c ) + { + boolean didSomething = false; + for( Object o : c ) + didSomething = this.remove( o ) || didSomething; + return didSomething; + } + + @Override + public boolean retainAll( Collection c ) + { + boolean changed = false; + Iterator i = this.iterator(); + + while( i.hasNext() ) + { + if( !c.contains( i.next() ) ) + { + i.remove(); + changed = true; + } + } + + return changed; + } + + @Override + public void clear() + { + Iterator i = this.myInterests.iterator(); + while( i.hasNext() ) + { + this.gsc.interestManager.remove( i.next(), this ); + i.remove(); + } + } + class ItemWatcherIterator implements Iterator { @@ -40,7 +163,8 @@ public class CraftingWatcher implements ICraftingWatcher final Iterator interestIterator; IAEStack myLast; - public ItemWatcherIterator(CraftingWatcher parent, Iterator i) { + public ItemWatcherIterator( CraftingWatcher parent, Iterator i ) + { this.watcher = parent; this.interestIterator = i; } @@ -63,127 +187,5 @@ public class CraftingWatcher implements ICraftingWatcher CraftingWatcher.this.gsc.interestManager.remove( this.myLast, this.watcher ); this.interestIterator.remove(); } - } - - final CraftingGridCache gsc; - final ICraftingWatcherHost host; - final HashSet myInterests = new HashSet(); - - public CraftingWatcher(CraftingGridCache cache, ICraftingWatcherHost host) { - this.gsc = cache; - this.host = host; - } - - public ICraftingWatcherHost getHost() - { - return this.host; - } - - @Override - public boolean add(IAEStack e) - { - if ( this.myInterests.contains( e ) ) - return false; - - return this.myInterests.add( e.copy() ) && this.gsc.interestManager.put( e, this ); - } - - @Override - public boolean addAll(Collection c) - { - boolean didChange = false; - - for (IAEStack o : c) - didChange = this.add( o ) || didChange; - - return didChange; - } - - @Override - public void clear() - { - Iterator i = this.myInterests.iterator(); - while (i.hasNext()) - { - this.gsc.interestManager.remove( i.next(), this ); - i.remove(); - } - } - - @Override - public boolean contains(Object o) - { - return this.myInterests.contains( o ); - } - - @Override - public boolean containsAll(Collection c) - { - return this.myInterests.containsAll( c ); - } - - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } - - @Override - public Iterator iterator() - { - return new ItemWatcherIterator( this, this.myInterests.iterator() ); - } - - @Override - public boolean remove(Object o) - { - return this.myInterests.remove( o ) && this.gsc.interestManager.remove( (IAEStack) o, this ); - } - - @Override - public boolean removeAll(Collection c) - { - boolean didSomething = false; - for (Object o : c) - didSomething = this.remove( o ) || didSomething; - return didSomething; - } - - @Override - public boolean retainAll(Collection c) - { - boolean changed = false; - Iterator i = this.iterator(); - - while (i.hasNext()) - { - if ( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } - - return changed; - } - - @Override - public int size() - { - return this.myInterests.size(); - } - - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } - - @Override - public T[] toArray(T[] a) - { - return this.myInterests.toArray( a ); - } - } diff --git a/src/main/java/appeng/crafting/MECraftingInventory.java b/src/main/java/appeng/crafting/MECraftingInventory.java index 0d7cb059e..c9a42eafb 100644 --- a/src/main/java/appeng/crafting/MECraftingInventory.java +++ b/src/main/java/appeng/crafting/MECraftingInventory.java @@ -18,6 +18,7 @@ package appeng.crafting; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -27,6 +28,7 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; + public class MECraftingInventory implements IMEInventory { @@ -57,24 +59,24 @@ public class MECraftingInventory implements IMEInventory this.par = null; } - public MECraftingInventory(MECraftingInventory parent) + public MECraftingInventory( MECraftingInventory parent ) { this.target = parent; this.logExtracted = parent.logExtracted; this.logInjections = parent.logInjections; this.logMissing = parent.logMissing; - if ( this.logMissing ) + if( this.logMissing ) this.missingCache = AEApi.instance().storage().createItemList(); else this.missingCache = null; - if ( this.logExtracted ) + if( this.logExtracted ) this.extractedCache = AEApi.instance().storage().createItemList(); else this.extractedCache = null; - if ( this.logInjections ) + if( this.logInjections ) this.injectedCache = AEApi.instance().storage().createItemList(); else this.injectedCache = null; @@ -84,53 +86,53 @@ public class MECraftingInventory implements IMEInventory this.par = parent; } - public MECraftingInventory(IMEMonitor target, BaseActionSource src, boolean logExtracted, boolean logInjections, boolean logMissing) + public MECraftingInventory( IMEMonitor target, BaseActionSource src, boolean logExtracted, boolean logInjections, boolean logMissing ) { this.target = target; this.logExtracted = logExtracted; this.logInjections = logInjections; this.logMissing = logMissing; - if ( logMissing ) + if( logMissing ) this.missingCache = AEApi.instance().storage().createItemList(); else this.missingCache = null; - if ( logExtracted ) + if( logExtracted ) this.extractedCache = AEApi.instance().storage().createItemList(); else this.extractedCache = null; - if ( logInjections ) + if( logInjections ) this.injectedCache = AEApi.instance().storage().createItemList(); else this.injectedCache = null; this.localCache = AEApi.instance().storage().createItemList(); - for (IAEItemStack is : target.getStorageList()) + for( IAEItemStack is : target.getStorageList() ) this.localCache.add( target.extractItems( is, Actionable.SIMULATE, src ) ); this.par = null; } - public MECraftingInventory(IMEInventory target, boolean logExtracted, boolean logInjections, boolean logMissing) + public MECraftingInventory( IMEInventory target, boolean logExtracted, boolean logInjections, boolean logMissing ) { this.target = target; this.logExtracted = logExtracted; this.logInjections = logInjections; this.logMissing = logMissing; - if ( logMissing ) + if( logMissing ) this.missingCache = AEApi.instance().storage().createItemList(); else this.missingCache = null; - if ( logExtracted ) + if( logExtracted ) this.extractedCache = AEApi.instance().storage().createItemList(); else this.extractedCache = null; - if ( logInjections ) + if( logInjections ) this.injectedCache = AEApi.instance().storage().createItemList(); else this.injectedCache = null; @@ -140,14 +142,14 @@ public class MECraftingInventory implements IMEInventory } @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable mode, BaseActionSource src) + public IAEItemStack injectItems( IAEItemStack input, Actionable mode, BaseActionSource src ) { - if ( input == null ) + if( input == null ) return null; - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) { - if ( this.logInjections ) + if( this.logInjections ) this.injectedCache.add( input ); this.localCache.add( input ); } @@ -156,21 +158,21 @@ public class MECraftingInventory implements IMEInventory } @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) + public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) { - if ( request == null ) + if( request == null ) return null; IAEItemStack list = this.localCache.findPrecise( request ); - if ( list == null || list.getStackSize() == 0 ) + if( list == null || list.getStackSize() == 0 ) return null; - if ( list.getStackSize() >= request.getStackSize() ) + if( list.getStackSize() >= request.getStackSize() ) { - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) { list.decStackSize( request.getStackSize() ); - if ( this.logExtracted ) + if( this.logExtracted ) this.extractedCache.add( request ); } @@ -180,10 +182,10 @@ public class MECraftingInventory implements IMEInventory IAEItemStack ret = request.copy(); ret.setStackSize( list.getStackSize() ); - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) { list.reset(); - if ( this.logExtracted ) + if( this.logExtracted ) this.extractedCache.add( ret ); } @@ -191,39 +193,39 @@ public class MECraftingInventory implements IMEInventory } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { - for (IAEItemStack is : this.localCache) + for( IAEItemStack is : this.localCache ) out.add( is ); return out; } - public IItemList getItemList() - { - return this.localCache; - } - @Override public StorageChannel getChannel() { return StorageChannel.ITEMS; } - public boolean commit(BaseActionSource src) + public IItemList getItemList() + { + return this.localCache; + } + + public boolean commit( BaseActionSource src ) { IItemList added = AEApi.instance().storage().createItemList(); IItemList pulled = AEApi.instance().storage().createItemList(); boolean failed = false; - if ( this.logInjections ) + if( this.logInjections ) { - for (IAEItemStack inject : this.injectedCache) + for( IAEItemStack inject : this.injectedCache ) { IAEItemStack result = null; added.add( result = this.target.injectItems( inject, Actionable.MODULATE, src ) ); - if ( result != null ) + if( result != null ) { failed = true; break; @@ -231,22 +233,22 @@ public class MECraftingInventory implements IMEInventory } } - if ( failed ) + if( failed ) { - for (IAEItemStack is : added) + for( IAEItemStack is : added ) this.target.extractItems( is, Actionable.MODULATE, src ); return false; } - if ( this.logExtracted ) + if( this.logExtracted ) { - for (IAEItemStack extra : this.extractedCache) + for( IAEItemStack extra : this.extractedCache ) { IAEItemStack result = null; pulled.add( result = this.target.extractItems( extra, Actionable.MODULATE, src ) ); - if ( result == null || result.getStackSize() != extra.getStackSize() ) + if( result == null || result.getStackSize() != extra.getStackSize() ) { failed = true; break; @@ -254,35 +256,35 @@ public class MECraftingInventory implements IMEInventory } } - if ( failed ) + if( failed ) { - for (IAEItemStack is : added) + for( IAEItemStack is : added ) this.target.extractItems( is, Actionable.MODULATE, src ); - for (IAEItemStack is : pulled) + for( IAEItemStack is : pulled ) this.target.injectItems( is, Actionable.MODULATE, src ); return false; } - if ( this.logMissing && this.par != null ) + if( this.logMissing && this.par != null ) { - for (IAEItemStack extra : this.missingCache) + for( IAEItemStack extra : this.missingCache ) this.par.addMissing( extra ); } return true; } - public void addMissing(IAEItemStack extra) + public void addMissing( IAEItemStack extra ) { this.missingCache.add( extra ); } - public void ignore(IAEItemStack what) + public void ignore( IAEItemStack what ) { IAEItemStack list = this.localCache.findPrecise( what ); - if ( list != null ) + if( list != null ) list.setStackSize( 0 ); } } diff --git a/src/main/java/appeng/debug/BlockChunkloader.java b/src/main/java/appeng/debug/BlockChunkloader.java index 3dcc52c7d..83a634ee7 100644 --- a/src/main/java/appeng/debug/BlockChunkloader.java +++ b/src/main/java/appeng/debug/BlockChunkloader.java @@ -18,6 +18,7 @@ package appeng.debug; + import java.util.EnumSet; import java.util.List; @@ -32,10 +33,12 @@ import appeng.block.AEBaseBlock; import appeng.core.AppEng; import appeng.core.features.AEFeature; + public class BlockChunkloader extends AEBaseBlock implements LoadingCallback { - public BlockChunkloader() { + public BlockChunkloader() + { super( BlockChunkloader.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); this.setTileEntity( TileChunkLoader.class ); @@ -43,15 +46,14 @@ public class BlockChunkloader extends AEBaseBlock implements LoadingCallback } @Override - public void ticketsLoaded(List tickets, World world) + public void ticketsLoaded( List tickets, World world ) { } @Override - public void registerBlockIcons(IIconRegister iconRegistry) + public void registerBlockIcons( IIconRegister iconRegistry ) { this.registerNoIcons(); } - } diff --git a/src/main/java/appeng/debug/BlockCubeGenerator.java b/src/main/java/appeng/debug/BlockCubeGenerator.java index b0ba015af..de109c60a 100644 --- a/src/main/java/appeng/debug/BlockCubeGenerator.java +++ b/src/main/java/appeng/debug/BlockCubeGenerator.java @@ -18,6 +18,7 @@ package appeng.debug; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -28,30 +29,31 @@ import net.minecraft.world.World; import appeng.block.AEBaseBlock; import appeng.core.features.AEFeature; + public class BlockCubeGenerator extends AEBaseBlock { - public BlockCubeGenerator() { + public BlockCubeGenerator() + { super( BlockCubeGenerator.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); this.setTileEntity( TileCubeGenerator.class ); } @Override - public boolean onActivated(World w, int x, int y, int z, - EntityPlayer player, int side, float hitX, float hitY, float hitZ) { + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) + { - TileCubeGenerator tcg = this.getTileEntity(w, x, y, z); - if ( tcg != null ) + TileCubeGenerator tcg = this.getTileEntity( w, x, y, z ); + if( tcg != null ) tcg.click( player ); return true; } @Override - public void registerBlockIcons(IIconRegister iconRegistry) + public void registerBlockIcons( IIconRegister iconRegistry ) { this.registerNoIcons(); } - } diff --git a/src/main/java/appeng/debug/BlockItemGen.java b/src/main/java/appeng/debug/BlockItemGen.java index ba4dbe669..50d24a0e5 100644 --- a/src/main/java/appeng/debug/BlockItemGen.java +++ b/src/main/java/appeng/debug/BlockItemGen.java @@ -18,6 +18,7 @@ package appeng.debug; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -26,19 +27,20 @@ import net.minecraft.client.renderer.texture.IIconRegister; import appeng.block.AEBaseBlock; import appeng.core.features.AEFeature; + public class BlockItemGen extends AEBaseBlock { - public BlockItemGen() { + public BlockItemGen() + { super( BlockItemGen.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); this.setTileEntity( TileItemGen.class ); } @Override - public void registerBlockIcons(IIconRegister iconRegistry) + public void registerBlockIcons( IIconRegister iconRegistry ) { this.registerNoIcons(); } - } diff --git a/src/main/java/appeng/debug/BlockPhantomNode.java b/src/main/java/appeng/debug/BlockPhantomNode.java index 772a64afc..626ac0278 100644 --- a/src/main/java/appeng/debug/BlockPhantomNode.java +++ b/src/main/java/appeng/debug/BlockPhantomNode.java @@ -18,6 +18,7 @@ package appeng.debug; + import java.util.EnumSet; import net.minecraft.block.material.Material; @@ -28,17 +29,19 @@ import net.minecraft.world.World; import appeng.block.AEBaseBlock; import appeng.core.features.AEFeature; + public class BlockPhantomNode extends AEBaseBlock { - public BlockPhantomNode() { + public BlockPhantomNode() + { super( BlockPhantomNode.class, Material.iron ); this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); this.setTileEntity( TilePhantomNode.class ); } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) + public boolean onActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) { TilePhantomNode tpn = this.getTileEntity( w, x, y, z ); tpn.BOOM(); @@ -46,9 +49,8 @@ public class BlockPhantomNode extends AEBaseBlock } @Override - public void registerBlockIcons(IIconRegister iconRegistry) + public void registerBlockIcons( IIconRegister iconRegistry ) { this.registerNoIcons(); } - } diff --git a/src/main/java/appeng/debug/TileChunkLoader.java b/src/main/java/appeng/debug/TileChunkLoader.java index c45d3c23d..f8aa77271 100644 --- a/src/main/java/appeng/debug/TileChunkLoader.java +++ b/src/main/java/appeng/debug/TileChunkLoader.java @@ -18,6 +18,7 @@ package appeng.debug; + import java.util.List; import net.minecraft.entity.player.EntityPlayerMP; @@ -37,16 +38,17 @@ import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.util.Platform; + public class TileChunkLoader extends AEBaseTile { boolean requestTicket = true; Ticket ct; - @TileEvent(TileEventType.TICK) + @TileEvent( TileEventType.TICK ) public void Tick_TileChunkLoader() { - if ( this.requestTicket ) + if( this.requestTicket ) { this.requestTicket = false; this.initTicket(); @@ -55,18 +57,18 @@ public class TileChunkLoader extends AEBaseTile void initTicket() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; this.ct = ForgeChunkManager.requestTicket( AppEng.instance, this.worldObj, Type.NORMAL ); - if ( this.ct == null ) + if( this.ct == null ) { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if ( server != null ) + if( server != null ) { List pl = server.getConfigurationManager().playerEntityList; - for (EntityPlayerMP p : pl) + for( EntityPlayerMP p : pl ) { p.addChatMessage( new ChatComponentText( "Can't chunk load.." ) ); } @@ -81,7 +83,7 @@ public class TileChunkLoader extends AEBaseTile @Override public void invalidate() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; AELog.info( "Released Ticket " + this.ct.toString() ); diff --git a/src/main/java/appeng/debug/TileCubeGenerator.java b/src/main/java/appeng/debug/TileCubeGenerator.java index 14ab93853..b059f2107 100644 --- a/src/main/java/appeng/debug/TileCubeGenerator.java +++ b/src/main/java/appeng/debug/TileCubeGenerator.java @@ -18,6 +18,7 @@ package appeng.debug; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -30,6 +31,7 @@ import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.util.Platform; + public class TileCubeGenerator extends AEBaseTile { @@ -38,22 +40,22 @@ public class TileCubeGenerator extends AEBaseTile int countdown = 20 * 10; EntityPlayer who; - @TileEvent(TileEventType.TICK) + @TileEvent( TileEventType.TICK ) public void TCG_Tick() { - if ( this.is != null && Platform.isServer() ) + if( this.is != null && Platform.isServer() ) { this.countdown--; - if ( this.countdown % 20 == 0 ) + if( this.countdown % 20 == 0 ) { - for (EntityPlayer e : CommonHelper.proxy.getPlayers()) + for( EntityPlayer e : CommonHelper.proxy.getPlayers() ) { - e.addChatMessage( new ChatComponentText( "Spawning in... " + (this.countdown / 20) ) ); + e.addChatMessage( new ChatComponentText( "Spawning in... " + ( this.countdown / 20 ) ) ); } } - if ( this.countdown <= 0 ) + if( this.countdown <= 0 ) this.spawn(); } } @@ -67,11 +69,11 @@ public class TileCubeGenerator extends AEBaseTile int half = (int) Math.floor( this.size / 2 ); - for (int y = 0; y < this.size; y++) + for( int y = 0; y < this.size; y++ ) { - for (int x = -half; x < half; x++) + for( int x = -half; x < half; x++ ) { - for (int z = -half; z < half; z++) + for( int z = -half; z < half; z++ ) { i.onItemUse( this.is.copy(), this.who, this.worldObj, x + this.xCoord, y + this.yCoord - 1, z + this.zCoord, side, 0.5f, 0.0f, 0.5f ); } @@ -79,25 +81,25 @@ public class TileCubeGenerator extends AEBaseTile } } - public void click(EntityPlayer player) + public void click( EntityPlayer player ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) { ItemStack hand = player.inventory.getCurrentItem(); this.who = player; - if ( hand == null ) + if( hand == null ) { this.is = null; - if ( player.isSneaking() ) + if( player.isSneaking() ) this.size--; else this.size++; - if ( this.size < 3 ) + if( this.size < 3 ) this.size = 3; - if ( this.size > 64 ) + if( this.size > 64 ) this.size = 64; player.addChatMessage( new ChatComponentText( "Size: " + this.size ) ); @@ -109,5 +111,4 @@ public class TileCubeGenerator extends AEBaseTile } } } - } diff --git a/src/main/java/appeng/debug/TileItemGen.java b/src/main/java/appeng/debug/TileItemGen.java index 35d783cda..f759f67cd 100644 --- a/src/main/java/appeng/debug/TileItemGen.java +++ b/src/main/java/appeng/debug/TileItemGen.java @@ -18,6 +18,7 @@ package appeng.debug; + import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -30,22 +31,24 @@ import net.minecraft.item.ItemStack; import appeng.tile.AEBaseTile; + public class TileItemGen extends AEBaseTile implements IInventory { private static final Queue POSSIBLE_ITEMS = new LinkedList(); - public TileItemGen() { - if ( POSSIBLE_ITEMS.isEmpty() ) + public TileItemGen() + { + if( POSSIBLE_ITEMS.isEmpty() ) { - for (Object obj : Item.itemRegistry) + for( Object obj : Item.itemRegistry ) { Item mi = (Item) obj; - if ( mi != null ) + if( mi != null ) { - if ( mi.isDamageable() ) + if( mi.isDamageable() ) { - for (int dmg = 0; dmg < mi.getMaxDamage(); dmg++) + for( int dmg = 0; dmg < mi.getMaxDamage(); dmg++ ) POSSIBLE_ITEMS.add( new ItemStack( mi, 1, dmg ) ); } else @@ -66,7 +69,7 @@ public class TileItemGen extends AEBaseTile implements IInventory } @Override - public ItemStack getStackInSlot(int i) + public ItemStack getStackInSlot( int i ) { return this.getRandomItem(); } @@ -77,7 +80,7 @@ public class TileItemGen extends AEBaseTile implements IInventory } @Override - public ItemStack decrStackSize(int i, int j) + public ItemStack decrStackSize( int i, int j ) { ItemStack a = POSSIBLE_ITEMS.poll(); ItemStack out = a.copy(); @@ -86,13 +89,13 @@ public class TileItemGen extends AEBaseTile implements IInventory } @Override - public ItemStack getStackInSlotOnClosing(int i) + public ItemStack getStackInSlotOnClosing( int i ) { return null; } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public void setInventorySlotContents( int i, ItemStack itemstack ) { ItemStack a = POSSIBLE_ITEMS.poll(); POSSIBLE_ITEMS.add( a ); @@ -116,6 +119,12 @@ public class TileItemGen extends AEBaseTile implements IInventory return 1; } + @Override + public boolean isUseableByPlayer( EntityPlayer entityplayer ) + { + return false; + } + @Override public void openInventory() { @@ -129,15 +138,8 @@ public class TileItemGen extends AEBaseTile implements IInventory } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { return false; } - - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) - { - return false; - } - } diff --git a/src/main/java/appeng/debug/TilePhantomNode.java b/src/main/java/appeng/debug/TilePhantomNode.java index f5472b950..7ec318101 100644 --- a/src/main/java/appeng/debug/TilePhantomNode.java +++ b/src/main/java/appeng/debug/TilePhantomNode.java @@ -18,6 +18,7 @@ package appeng.debug; + import java.util.EnumSet; import net.minecraftforge.common.util.ForgeDirection; @@ -26,12 +27,22 @@ import appeng.api.networking.IGridNode; import appeng.me.helpers.AENetworkProxy; import appeng.tile.grid.AENetworkTile; + public class TilePhantomNode extends AENetworkTile { protected AENetworkProxy proxy = null; boolean crashMode = false; + @Override + public IGridNode getGridNode( ForgeDirection dir ) + { + if( !this.crashMode ) + return super.getGridNode( dir ); + + return this.proxy.getNode(); + } + @Override public void onReady() { @@ -41,18 +52,9 @@ public class TilePhantomNode extends AENetworkTile this.crashMode = true; } - @Override - public IGridNode getGridNode(ForgeDirection dir) - { - if ( !this.crashMode ) - return super.getGridNode( dir ); - - return this.proxy.getNode(); - } - public void BOOM() { - if ( this.proxy != null ) + if( this.proxy != null ) { this.crashMode = true; this.proxy.setValidSides( EnumSet.allOf( ForgeDirection.class ) ); diff --git a/src/main/java/appeng/debug/ToolDebugCard.java b/src/main/java/appeng/debug/ToolDebugCard.java index 195280845..46f3c9070 100644 --- a/src/main/java/appeng/debug/ToolDebugCard.java +++ b/src/main/java/appeng/debug/ToolDebugCard.java @@ -62,15 +62,15 @@ public class ToolDebugCard extends AEBaseItem @Override public boolean onItemUseFirst( ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return false; - if ( player.isSneaking() ) + if( player.isSneaking() ) { int grids = 0; int totalNodes = 0; - for ( Grid g : TickHandler.INSTANCE.getGridList() ) + for( Grid g : TickHandler.INSTANCE.getGridList() ) { grids++; totalNodes += g.getNodes().size(); @@ -83,10 +83,10 @@ public class ToolDebugCard extends AEBaseItem { TileEntity te = world.getTileEntity( x, y, z ); - if ( te instanceof IGridHost ) + if( te instanceof IGridHost ) { GridNode node = (GridNode) ( (IGridHost) te ).getGridNode( ForgeDirection.getOrientation( side ) ); - if ( node != null ) + if( node != null ) { Grid g = node.getInternalGrid(); IGridNode center = g.getPivot(); @@ -94,7 +94,7 @@ public class ToolDebugCard extends AEBaseItem this.outputMsg( player, "Center Node: " + center.toString() ); IPathingGrid pg = g.getCache( IPathingGrid.class ); - if ( pg.getControllerState() == ControllerState.CONTROLLER_ONLINE ) + if( pg.getControllerState() == ControllerState.CONTROLLER_ONLINE ) { int length = 0; @@ -104,46 +104,46 @@ public class ToolDebugCard extends AEBaseItem int maxLength = 10000; outer: - while ( !next.isEmpty() ) + while( !next.isEmpty() ) { Iterable current = next; next = new HashSet(); - for ( IGridNode n : current ) + for( IGridNode n : current ) { - if ( n.getMachine() instanceof TileController ) + if( n.getMachine() instanceof TileController ) break outer; - for ( IGridConnection c : n.getConnections() ) + for( IGridConnection c : n.getConnections() ) next.add( c.getOtherSide( n ) ); } length++; - if ( length > maxLength ) + if( length > maxLength ) break; } this.outputMsg( player, "Cable Distance: " + length ); } - if ( center.getMachine() instanceof PartP2PTunnel ) + if( center.getMachine() instanceof PartP2PTunnel ) { this.outputMsg( player, "Freq: " + ( (PartP2PTunnel) center.getMachine() ).freq ); } TickManagerCache tmc = g.getCache( ITickManager.class ); - for ( Class c : g.getMachineClasses() ) + for( Class c : g.getMachineClasses() ) { int o = 0; long nanos = 0; - for ( IGridNode oj : g.getMachines( c ) ) + for( IGridNode oj : g.getMachines( c ) ) { o++; nanos += tmc.getAvgNanoTime( oj ); } - if ( nanos < 0 ) + if( nanos < 0 ) { this.outputMsg( player, c.getSimpleName() + " - " + o ); } @@ -159,32 +159,32 @@ public class ToolDebugCard extends AEBaseItem else this.outputMsg( player, "Not Networked Block" ); - if ( te instanceof IPartHost ) + if( te instanceof IPartHost ) { IPart center = ( (IPartHost) te ).getPart( ForgeDirection.UNKNOWN ); ( (IPartHost) te ).markForUpdate(); - if ( center != null ) + if( center != null ) { GridNode n = (GridNode) center.getGridNode(); this.outputMsg( player, "Node Channels: " + n.usedChannels() ); - for ( IGridConnection gc : n.getConnections() ) + for( IGridConnection gc : n.getConnections() ) { ForgeDirection fd = gc.getDirection( n ); - if ( fd != ForgeDirection.UNKNOWN ) + if( fd != ForgeDirection.UNKNOWN ) this.outputMsg( player, fd.toString() + ": " + gc.getUsedChannels() ); } } } - if ( te instanceof IAEPowerStorage ) + if( te instanceof IAEPowerStorage ) { IAEPowerStorage ps = (IAEPowerStorage) te; this.outputMsg( player, "Energy: " + ps.getAECurrentPower() + " / " + ps.getAEMaxPower() ); - if ( te instanceof IGridHost ) + if( te instanceof IGridHost ) { IGridNode node = ( (IGridHost) te ).getGridNode( ForgeDirection.getOrientation( side ) ); - if ( node != null && node.getGrid() != null ) + if( node != null && node.getGrid() != null ) { IEnergyGrid eg = node.getGrid().getCache( IEnergyGrid.class ); this.outputMsg( player, "GridEnergy: " + eg.getStoredPower() + " : " + eg.getEnergyDemand( Double.MAX_VALUE ) ); @@ -203,7 +203,7 @@ public class ToolDebugCard extends AEBaseItem public String timeMeasurement( long nanos ) { long ms = nanos / 100000; - if ( nanos <= 100000 ) + if( nanos <= 100000 ) return nanos + "ns"; return ( ms / 10.0f ) + "ms"; } diff --git a/src/main/java/appeng/debug/ToolEraser.java b/src/main/java/appeng/debug/ToolEraser.java index c4d07caea..13448d9f0 100644 --- a/src/main/java/appeng/debug/ToolEraser.java +++ b/src/main/java/appeng/debug/ToolEraser.java @@ -57,7 +57,7 @@ public class ToolEraser extends AEBaseItem @Override public boolean onItemUseFirst( ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return false; Block blk = world.getBlock( x, y, z ); @@ -67,17 +67,17 @@ public class ToolEraser extends AEBaseItem List next = new LinkedList(); next.add( new WorldCoord( x, y, z ) ); - while ( blocks < BLOCK_ERASE_LIMIT && !next.isEmpty() ) + while( blocks < BLOCK_ERASE_LIMIT && !next.isEmpty() ) { List c = next; next = new LinkedList(); - for ( WorldCoord wc : c ) + for( WorldCoord wc : c ) { Block c_blk = world.getBlock( wc.x, wc.y, wc.z ); int c_meta = world.getBlockMetadata( wc.x, wc.y, wc.z ); - if ( c_blk == blk && c_meta == meta ) + if( c_blk == blk && c_meta == meta ) { blocks++; world.setBlock( wc.x, wc.y, wc.z, Platform.AIR ); diff --git a/src/main/java/appeng/debug/ToolMeteoritePlacer.java b/src/main/java/appeng/debug/ToolMeteoritePlacer.java index a60a45485..c5dbb1354 100644 --- a/src/main/java/appeng/debug/ToolMeteoritePlacer.java +++ b/src/main/java/appeng/debug/ToolMeteoritePlacer.java @@ -29,10 +29,10 @@ import net.minecraft.world.World; import appeng.client.texture.MissingIcon; import appeng.core.features.AEFeature; -import appeng.worldgen.MeteoritePlacer; -import appeng.worldgen.meteorite.StandardWorld; import appeng.items.AEBaseItem; import appeng.util.Platform; +import appeng.worldgen.MeteoritePlacer; +import appeng.worldgen.meteorite.StandardWorld; public class ToolMeteoritePlacer extends AEBaseItem @@ -51,13 +51,13 @@ public class ToolMeteoritePlacer extends AEBaseItem @Override public boolean onItemUseFirst( ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return false; MeteoritePlacer mp = new MeteoritePlacer(); boolean worked = mp.spawnMeteorite( new StandardWorld( world ), x, y, z ); - if ( !worked ) + if( !worked ) player.addChatMessage( new ChatComponentText( "Un-suitable Location." ) ); return true; diff --git a/src/main/java/appeng/debug/ToolReplicatorCard.java b/src/main/java/appeng/debug/ToolReplicatorCard.java index 148dc7877..f41ec0f8c 100644 --- a/src/main/java/appeng/debug/ToolReplicatorCard.java +++ b/src/main/java/appeng/debug/ToolReplicatorCard.java @@ -52,12 +52,12 @@ public class ToolReplicatorCard extends AEBaseItem @Override public boolean onItemUseFirst( ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return false; - if ( player.isSneaking() ) + if( player.isSneaking() ) { - if ( world.getTileEntity( x, y, z ) instanceof IGridHost ) + if( world.getTileEntity( x, y, z ) instanceof IGridHost ) { NBTTagCompound tag = new NBTTagCompound(); tag.setInteger( "x", x ); @@ -73,7 +73,7 @@ public class ToolReplicatorCard extends AEBaseItem else { NBTTagCompound ish = stack.getTagCompound(); - if ( ish != null ) + if( ish != null ) { int src_x = ish.getInteger( "x" ); int src_y = ish.getInteger( "y" ); @@ -83,19 +83,19 @@ public class ToolReplicatorCard extends AEBaseItem World src_w = DimensionManager.getWorld( dimid ); TileEntity te = src_w.getTileEntity( src_x, src_y, src_z ); - if ( te instanceof IGridHost ) + if( te instanceof IGridHost ) { IGridHost gh = (IGridHost) te; ForgeDirection sideOff = ForgeDirection.getOrientation( src_side ); ForgeDirection currentSideOff = ForgeDirection.getOrientation( side ); IGridNode n = gh.getGridNode( sideOff ); - if ( n != null ) + if( n != null ) { IGrid g = n.getGrid(); - if ( g != null ) + if( g != null ) { ISpatialCache sc = g.getCache( ISpatialCache.class ); - if ( sc.isValidRegion() ) + if( sc.isValidRegion() ) { DimensionalCoord min = sc.getMin(); DimensionalCoord max = sc.getMax(); @@ -116,15 +116,15 @@ public class ToolReplicatorCard extends AEBaseItem int scale_y = max.y - min.y; int scale_z = max.z - min.z; - for ( int i = 1; i < scale_x; i++ ) - for ( int j = 1; j < scale_y; j++ ) - for ( int k = 1; k < scale_z; k++ ) + for( int i = 1; i < scale_x; i++ ) + for( int j = 1; j < scale_y; j++ ) + for( int k = 1; k < scale_z; k++ ) { Block blk = src_w.getBlock( min_x + i, min_y + j, min_z + k ); int meta = src_w.getBlockMetadata( min_x + i, min_y + j, min_z + k ); world.setBlock( i + rel_x, j + rel_y, k + rel_z, blk, meta, 4 ); - if ( blk != null && blk.hasTileEntity( meta ) ) + if( blk != null && blk.hasTileEntity( meta ) ) { TileEntity ote = src_w.getTileEntity( min_x + i, min_y + j, min_z + k ); TileEntity nte = blk.createTileEntity( world, meta ); diff --git a/src/main/java/appeng/entity/EntityChargedQuartz.java b/src/main/java/appeng/entity/EntityChargedQuartz.java index 4a276bdf5..90129bb7c 100644 --- a/src/main/java/appeng/entity/EntityChargedQuartz.java +++ b/src/main/java/appeng/entity/EntityChargedQuartz.java @@ -18,6 +18,7 @@ package appeng.entity; + import java.util.List; import net.minecraft.block.material.Material; @@ -38,6 +39,7 @@ import appeng.core.features.AEFeature; import appeng.helpers.Reflected; import appeng.util.Platform; + final public class EntityChargedQuartz extends AEBaseEntityItem { @@ -45,12 +47,12 @@ final public class EntityChargedQuartz extends AEBaseEntityItem int transformTime = 0; @Reflected - public EntityChargedQuartz(World w) + public EntityChargedQuartz( World w ) { super( w ); } - public EntityChargedQuartz(World w, double x, double y, double z, ItemStack is) + public EntityChargedQuartz( World w, double x, double y, double z, ItemStack is ) { super( w, x, y, z, is ); } @@ -60,10 +62,10 @@ final public class EntityChargedQuartz extends AEBaseEntityItem { super.onUpdate(); - if ( !AEConfig.instance.isFeatureEnabled( AEFeature.inWorldFluix ) ) + if( !AEConfig.instance.isFeatureEnabled( AEFeature.inWorldFluix ) ) return; - if ( Platform.isClient() && this.delay > 30 && AEConfig.instance.enableEffects ) + if( Platform.isClient() && this.delay > 30 && AEConfig.instance.enableEffects ) { CommonHelper.proxy.spawnEffect( EffectType.Lightning, this.worldObj, this.posX, this.posY, this.posZ, null ); this.delay = 0; @@ -75,12 +77,12 @@ final public class EntityChargedQuartz extends AEBaseEntityItem int k = MathHelper.floor_double( this.posZ ); Material mat = this.worldObj.getBlock( j, i, k ).getMaterial(); - if ( Platform.isServer() && mat.isLiquid() ) + if( Platform.isServer() && mat.isLiquid() ) { this.transformTime++; - if ( this.transformTime > 60 ) + if( this.transformTime > 60 ) { - if ( !this.transform() ) + if( !this.transform() ) this.transformTime = 0; } } @@ -93,7 +95,7 @@ final public class EntityChargedQuartz extends AEBaseEntityItem ItemStack item = this.getEntityItem(); final IMaterials materials = AEApi.instance().definitions().materials(); - if ( materials.certusQuartzCrystalCharged().isSameAs( item ) ) + if( materials.certusQuartzCrystalCharged().isSameAs( item ) ) { AxisAlignedBB region = AxisAlignedBB.getBoundingBox( this.posX - 1, this.posY - 1, this.posZ - 1, this.posX + 1, this.posY + 1, this.posZ + 1 ); List l = this.getCheckedEntitiesWithinAABBExcludingEntity( region ); @@ -101,38 +103,38 @@ final public class EntityChargedQuartz extends AEBaseEntityItem EntityItem redstone = null; EntityItem netherQuartz = null; - for (Entity e : l) + for( Entity e : l ) { - if ( e instanceof EntityItem && !e.isDead ) + if( e instanceof EntityItem && !e.isDead ) { - ItemStack other = ((EntityItem) e).getEntityItem(); - if ( other != null && other.stackSize > 0 ) + ItemStack other = ( (EntityItem) e ).getEntityItem(); + if( other != null && other.stackSize > 0 ) { - if ( Platform.isSameItem( other, new ItemStack( Items.redstone ) ) ) + if( Platform.isSameItem( other, new ItemStack( Items.redstone ) ) ) redstone = (EntityItem) e; - if ( Platform.isSameItem( other, new ItemStack( Items.quartz ) ) ) + if( Platform.isSameItem( other, new ItemStack( Items.quartz ) ) ) netherQuartz = (EntityItem) e; } } } - if ( redstone != null && netherQuartz != null ) + if( redstone != null && netherQuartz != null ) { this.getEntityItem().stackSize--; redstone.getEntityItem().stackSize--; netherQuartz.getEntityItem().stackSize--; - if ( this.getEntityItem().stackSize <= 0 ) + if( this.getEntityItem().stackSize <= 0 ) this.setDead(); - if ( redstone.getEntityItem().stackSize <= 0 ) + if( redstone.getEntityItem().stackSize <= 0 ) redstone.setDead(); - if ( netherQuartz.getEntityItem().stackSize <= 0 ) + if( netherQuartz.getEntityItem().stackSize <= 0 ) netherQuartz.setDead(); - for ( ItemStack fluixCrystalStack : materials.fluixCrystal().maybeStack( 2 ).asSet() ) + for( ItemStack fluixCrystalStack : materials.fluixCrystal().maybeStack( 2 ).asSet() ) { final EntityItem entity = new EntityItem( this.worldObj, this.posX, this.posY, this.posZ, fluixCrystalStack ); diff --git a/src/main/java/appeng/entity/EntityFloatingItem.java b/src/main/java/appeng/entity/EntityFloatingItem.java index 0b340fea1..fe6e600f5 100644 --- a/src/main/java/appeng/entity/EntityFloatingItem.java +++ b/src/main/java/appeng/entity/EntityFloatingItem.java @@ -18,21 +18,23 @@ package appeng.entity; + import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.world.World; + final public class EntityFloatingItem extends EntityItem { public static int ageStatic = 0; - - int superDeath = 0; private final Entity parent; + int superDeath = 0; float progress = 0; - public EntityFloatingItem(Entity parent, World p_i1710_1_, double p_i1710_2_, double p_i1710_4_, double p_i1710_6_, ItemStack p_i1710_8_) { + public EntityFloatingItem( Entity parent, World p_i1710_1_, double p_i1710_2_, double p_i1710_4_, double p_i1710_6_, ItemStack p_i1710_8_ ) + { super( p_i1710_1_, p_i1710_2_, p_i1710_4_, p_i1710_6_, p_i1710_8_ ); this.motionX = this.motionY = this.motionZ = 0.0d; this.hoverStart = 0.5f; @@ -45,21 +47,20 @@ final public class EntityFloatingItem extends EntityItem @Override public void onUpdate() { - if ( !this.isDead && this.parent.isDead ) + if( !this.isDead && this.parent.isDead ) this.setDead(); - if ( this.superDeath > 100 ) + if( this.superDeath > 100 ) this.setDead(); this.superDeath++; this.age = ageStatic; } - public void setProgress(float progress) + public void setProgress( float progress ) { this.progress = progress; - if ( this.progress > 0.99 ) + if( this.progress > 0.99 ) this.setDead(); } - } diff --git a/src/main/java/appeng/entity/EntityGrowingCrystal.java b/src/main/java/appeng/entity/EntityGrowingCrystal.java index 5d196ea12..567c446df 100644 --- a/src/main/java/appeng/entity/EntityGrowingCrystal.java +++ b/src/main/java/appeng/entity/EntityGrowingCrystal.java @@ -18,6 +18,7 @@ package appeng.entity; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.item.EntityItem; @@ -35,16 +36,19 @@ import appeng.core.CommonHelper; import appeng.core.features.AEFeature; import appeng.util.Platform; + final public class EntityGrowingCrystal extends EntityItem { private int progress_1000 = 0; - public EntityGrowingCrystal(World w) { + public EntityGrowingCrystal( World w ) + { super( w ); } - public EntityGrowingCrystal(World w, double x, double y, double z, ItemStack is) { + public EntityGrowingCrystal( World w, double x, double y, double z, ItemStack is ) + { super( w, x, y, z, is ); } @@ -53,16 +57,16 @@ final public class EntityGrowingCrystal extends EntityItem { super.onUpdate(); - if ( !AEConfig.instance.isFeatureEnabled( AEFeature.inWorldPurification ) ) + if( !AEConfig.instance.isFeatureEnabled( AEFeature.inWorldPurification ) ) return; - if ( this.age > 600 ) + if( this.age > 600 ) this.age = 100; ItemStack is = this.getEntityItem(); Item gc = is.getItem(); - if ( gc instanceof IGrowableCrystal ) // if it changes this just stops being an issue... + if( gc instanceof IGrowableCrystal ) // if it changes this just stops being an issue... { int j = MathHelper.floor_double( this.posX ); int i = MathHelper.floor_double( this.posY ); @@ -77,40 +81,39 @@ final public class EntityGrowingCrystal extends EntityItem boolean isClient = Platform.isClient(); - if ( mat.isLiquid() ) + if( mat.isLiquid() ) { - if ( isClient ) + if( isClient ) this.progress_1000++; else this.progress_1000 += speed; - } else this.progress_1000 = 0; - if ( isClient ) + if( isClient ) { int len = 40; - if ( speed > 2 ) + if( speed > 2 ) len = 20; - if ( speed > 90 ) + if( speed > 90 ) len = 15; - if ( speed > 150 ) + if( speed > 150 ) len = 10; - if ( speed > 240 ) + if( speed > 240 ) len = 7; - if ( speed > 360 ) + if( speed > 360 ) len = 3; - if ( speed > 500 ) + if( speed > 500 ) len = 1; - if ( this.progress_1000 >= len ) + if( this.progress_1000 >= len ) { this.progress_1000 = 0; CommonHelper.proxy.spawnEffect( EffectType.Vibrant, this.worldObj, this.posX, this.posY + 0.2, this.posZ, null ); @@ -118,7 +121,7 @@ final public class EntityGrowingCrystal extends EntityItem } else { - if ( this.progress_1000 > 1000 ) + if( this.progress_1000 > 1000 ) { this.progress_1000 -= 1000; this.setEntityItemStack( cry.triggerGrowth( is ) ); @@ -127,39 +130,38 @@ final public class EntityGrowingCrystal extends EntityItem } } - private int getSpeed(int x, int y, int z) + private int getSpeed( int x, int y, int z ) { final int per = 80; final float mul = 0.3f; int qty = 0; - if ( this.isAccelerated( x + 1, y, z ) ) + if( this.isAccelerated( x + 1, y, z ) ) qty += per + qty * mul; - if ( this.isAccelerated( x, y + 1, z ) ) + if( this.isAccelerated( x, y + 1, z ) ) qty += per + qty * mul; - if ( this.isAccelerated( x, y, z + 1 ) ) + if( this.isAccelerated( x, y, z + 1 ) ) qty += per + qty * mul; - if ( this.isAccelerated( x - 1, y, z ) ) + if( this.isAccelerated( x - 1, y, z ) ) qty += per + qty * mul; - if ( this.isAccelerated( x, y - 1, z ) ) + if( this.isAccelerated( x, y - 1, z ) ) qty += per + qty * mul; - if ( this.isAccelerated( x, y, z - 1 ) ) + if( this.isAccelerated( x, y, z - 1 ) ) qty += per + qty * mul; return qty; } - private boolean isAccelerated(int x, int y, int z) + private boolean isAccelerated( int x, int y, int z ) { TileEntity te = this.worldObj.getTileEntity( x, y, z ); - return te instanceof ICrystalGrowthAccelerator && ( ( ICrystalGrowthAccelerator ) te ).isPowered(); + return te instanceof ICrystalGrowthAccelerator && ( (ICrystalGrowthAccelerator) te ).isPowered(); } - } diff --git a/src/main/java/appeng/entity/EntitySingularity.java b/src/main/java/appeng/entity/EntitySingularity.java index 78fb5b9ba..4eadca8c3 100644 --- a/src/main/java/appeng/entity/EntitySingularity.java +++ b/src/main/java/appeng/entity/EntitySingularity.java @@ -58,7 +58,7 @@ final public class EntitySingularity extends AEBaseEntityItem @Override public boolean attackEntityFrom( DamageSource src, float dmg ) { - if ( src.isExplosion() ) + if( src.isExplosion() ) { this.doExplosion(); return false; @@ -69,32 +69,32 @@ final public class EntitySingularity extends AEBaseEntityItem public void doExplosion() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; - if ( !AEConfig.instance.isFeatureEnabled( AEFeature.inWorldSingularity ) ) + if( !AEConfig.instance.isFeatureEnabled( AEFeature.inWorldSingularity ) ) return; ItemStack item = this.getEntityItem(); final IMaterials materials = AEApi.instance().definitions().materials(); - if ( materials.singularity().isSameAs( item ) ) + if( materials.singularity().isSameAs( item ) ) { AxisAlignedBB region = AxisAlignedBB.getBoundingBox( this.posX - 4, this.posY - 4, this.posZ - 4, this.posX + 4, this.posY + 4, this.posZ + 4 ); List l = this.getCheckedEntitiesWithinAABBExcludingEntity( region ); - for ( Entity e : l ) + for( Entity e : l ) { - if ( e instanceof EntityItem ) + if( e instanceof EntityItem ) { - ItemStack other = ( ( EntityItem ) e ).getEntityItem(); - if ( other != null ) + ItemStack other = ( (EntityItem) e ).getEntityItem(); + if( other != null ) { boolean matches = false; - for ( ItemStack is : OreDictionary.getOres( "dustEnder" ) ) + for( ItemStack is : OreDictionary.getOres( "dustEnder" ) ) { - if ( OreDictionary.itemMatches( other, is, false ) ) + if( OreDictionary.itemMatches( other, is, false ) ) { matches = true; break; @@ -102,11 +102,11 @@ final public class EntitySingularity extends AEBaseEntityItem } // check... other name. - if ( !matches ) + if( !matches ) { - for ( ItemStack is : OreDictionary.getOres( "dustEnderPearl" ) ) + for( ItemStack is : OreDictionary.getOres( "dustEnderPearl" ) ) { - if ( OreDictionary.itemMatches( other, is, false ) ) + if( OreDictionary.itemMatches( other, is, false ) ) { matches = true; break; @@ -114,15 +114,15 @@ final public class EntitySingularity extends AEBaseEntityItem } } - if ( matches ) + if( matches ) { - while ( item.stackSize > 0 && other.stackSize > 0 ) + while( item.stackSize > 0 && other.stackSize > 0 ) { other.stackSize--; - if ( other.stackSize == 0 ) + if( other.stackSize == 0 ) e.setDead(); - for ( ItemStack singularityStack : materials.qESingularity().maybeStack( 2 ).asSet() ) + for( ItemStack singularityStack : materials.qESingularity().maybeStack( 2 ).asSet() ) { NBTTagCompound cmp = Platform.openNbtData( singularityStack ); cmp.setLong( "freq", ( new Date() ).getTime() * 100 + ( randTickSeed ) % 100 ); @@ -134,7 +134,7 @@ final public class EntitySingularity extends AEBaseEntityItem } } - if ( item.stackSize <= 0 ) + if( item.stackSize <= 0 ) this.setDead(); } } diff --git a/src/main/java/appeng/entity/EntityTinyTNTPrimed.java b/src/main/java/appeng/entity/EntityTinyTNTPrimed.java index 9d22d4019..bcd4e51da 100644 --- a/src/main/java/appeng/entity/EntityTinyTNTPrimed.java +++ b/src/main/java/appeng/entity/EntityTinyTNTPrimed.java @@ -18,6 +18,7 @@ package appeng.entity; + import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; @@ -42,15 +43,18 @@ import appeng.core.sync.packets.PacketMockExplosion; import appeng.helpers.Reflected; import appeng.util.Platform; + final public class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntityAdditionalSpawnData { @Reflected - public EntityTinyTNTPrimed(World w) { + public EntityTinyTNTPrimed( World w ) + { super( w ); this.setSize( 0.35F, 0.35F ); } - public EntityTinyTNTPrimed(World w, double x, double y, double z, EntityLivingBase igniter) { + public EntityTinyTNTPrimed( World w, double x, double y, double z, EntityLivingBase igniter ) + { super( w, x, y, z, igniter ); this.setSize( 0.55F, 0.55F ); this.yOffset = this.height / 2.0F; @@ -73,16 +77,16 @@ final public class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntit this.motionY *= 0.9800000190734863D; this.motionZ *= 0.9800000190734863D; - if ( this.onGround ) + if( this.onGround ) { this.motionX *= 0.699999988079071D; this.motionZ *= 0.699999988079071D; this.motionY *= -0.5D; } - if ( this.isInWater() && Platform.isServer() ) // put out the fuse. + if( this.isInWater() && Platform.isServer() ) // put out the fuse. { - for ( ItemStack tntStack : AEApi.instance().definitions().blocks().tinyTNT().maybeStack( 1 ).asSet() ) + for( ItemStack tntStack : AEApi.instance().definitions().blocks().tinyTNT().maybeStack( 1 ).asSet() ) { final EntityItem item = new EntityItem( this.worldObj, this.posX, this.posY, this.posZ, tntStack ); @@ -98,11 +102,11 @@ final public class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntit } } - if ( this.fuse <= 0 ) + if( this.fuse <= 0 ) { this.setDead(); - if ( !this.worldObj.isRemote ) + if( !this.worldObj.isRemote ) { this.explode(); } @@ -117,49 +121,45 @@ final public class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntit // override :P void explode() { - this.worldObj.playSoundEffect( this.posX, this.posY, this.posZ, "random.explode", 4.0F, - (1.0F + (this.worldObj.rand.nextFloat() - this.worldObj.rand.nextFloat()) * 0.2F) * 32.9F ); + this.worldObj.playSoundEffect( this.posX, this.posY, this.posZ, "random.explode", 4.0F, ( 1.0F + ( this.worldObj.rand.nextFloat() - this.worldObj.rand.nextFloat() ) * 0.2F ) * 32.9F ); - if ( this.isInWater() ) + if( this.isInWater() ) { return; } - for (Object e : this.worldObj.getEntitiesWithinAABBExcludingEntity( this, - AxisAlignedBB.getBoundingBox( this.posX - 1.5, this.posY - 1.5f, this.posZ - 1.5, this.posX + 1.5, this.posY + 1.5, this.posZ + 1.5 ) )) + for( Object e : this.worldObj.getEntitiesWithinAABBExcludingEntity( this, AxisAlignedBB.getBoundingBox( this.posX - 1.5, this.posY - 1.5f, this.posZ - 1.5, this.posX + 1.5, this.posY + 1.5, this.posZ + 1.5 ) ) ) { - if ( e instanceof Entity ) + if( e instanceof Entity ) { - ((Entity) e).attackEntityFrom( DamageSource.setExplosionSource( null ), 6 ); + ( (Entity) e ).attackEntityFrom( DamageSource.setExplosionSource( null ), 6 ); } - } - if ( AEConfig.instance.isFeatureEnabled( AEFeature.TinyTNTBlockDamage ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.TinyTNTBlockDamage ) ) { this.posY -= 0.25; Explosion ex = new Explosion( this.worldObj, this, this.posX, this.posY, this.posZ, 0.2f ); - for (int x = (int) (this.posX - 2); x <= this.posX + 2; x++) + for( int x = (int) ( this.posX - 2 ); x <= this.posX + 2; x++ ) { - for (int y = (int) (this.posY - 2); y <= this.posY + 2; y++) + for( int y = (int) ( this.posY - 2 ); y <= this.posY + 2; y++ ) { - for (int z = (int) (this.posZ - 2); z <= this.posZ + 2; z++) + for( int z = (int) ( this.posZ - 2 ); z <= this.posZ + 2; z++ ) { Block block = this.worldObj.getBlock( x, y, z ); - if ( block != null && !block.isAir( this.worldObj, x, y, z ) ) + if( block != null && !block.isAir( this.worldObj, x, y, z ) ) { - float strength = (float) (2.3f - (((x + 0.5f) - this.posX) * ((x + 0.5f) - this.posX) + ((y + 0.5f) - this.posY) * ((y + 0.5f) - this.posY) + ((z + 0.5f) - this.posZ) - * ((z + 0.5f) - this.posZ))); + float strength = (float) ( 2.3f - ( ( ( x + 0.5f ) - this.posX ) * ( ( x + 0.5f ) - this.posX ) + ( ( y + 0.5f ) - this.posY ) * ( ( y + 0.5f ) - this.posY ) + ( ( z + 0.5f ) - this.posZ ) * ( ( z + 0.5f ) - this.posZ ) ) ); float resistance = block.getExplosionResistance( this, this.worldObj, x, y, z, this.posX, this.posY, this.posZ ); - strength -= (resistance + 0.3F) * 0.11f; + strength -= ( resistance + 0.3F ) * 0.11f; - if ( strength > 0.01 ) + if( strength > 0.01 ) { - if ( block.getMaterial() != Material.air ) + if( block.getMaterial() != Material.air ) { - if ( block.canDropFromExplosion( ex ) ) + if( block.canDropFromExplosion( ex ) ) { block.dropBlockAsItemWithChance( this.worldObj, x, y, z, this.worldObj.getBlockMetadata( x, y, z ), 1.0F / 1.0f, 0 ); } @@ -167,7 +167,6 @@ final public class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntit block.onBlockExploded( this.worldObj, x, y, z, ex ); } } - } } } @@ -178,15 +177,14 @@ final public class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntit } @Override - public void writeSpawnData(ByteBuf data) + public void writeSpawnData( ByteBuf data ) { data.writeByte( this.fuse ); } @Override - public void readSpawnData(ByteBuf data) + public void readSpawnData( ByteBuf data ) { this.fuse = data.readByte(); } - } diff --git a/src/main/java/appeng/entity/RenderFloatingItem.java b/src/main/java/appeng/entity/RenderFloatingItem.java index df9739f90..82eb02071 100644 --- a/src/main/java/appeng/entity/RenderFloatingItem.java +++ b/src/main/java/appeng/entity/RenderFloatingItem.java @@ -18,6 +18,7 @@ package appeng.entity; + import java.nio.ByteBuffer; import java.nio.DoubleBuffer; @@ -31,34 +32,30 @@ import net.minecraft.item.ItemBlock; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -@SideOnly(Side.CLIENT) + +@SideOnly( Side.CLIENT ) public class RenderFloatingItem extends RenderItem { public static DoubleBuffer buffer = ByteBuffer.allocateDirect( 8 * 4 ).asDoubleBuffer(); - public RenderFloatingItem() { + public RenderFloatingItem() + { this.shadowOpaque = 0.0F; this.renderManager = RenderManager.instance; } @Override - public boolean shouldBob() + public void doRender( EntityItem p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_ ) { - return false; - } - - @Override - public void doRender(EntityItem p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_) - { - if ( p_76986_1_ instanceof EntityFloatingItem ) + if( p_76986_1_ instanceof EntityFloatingItem ) { EntityFloatingItem efi = (EntityFloatingItem) p_76986_1_; - if ( efi.progress > 0.0 ) + if( efi.progress > 0.0 ) { GL11.glPushMatrix(); - if ( !(efi.getEntityItem().getItem() instanceof ItemBlock) ) + if( !( efi.getEntityItem().getItem() instanceof ItemBlock ) ) GL11.glTranslatef( 0, -0.15f, 0 ); super.doRender( efi, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_ ); @@ -67,4 +64,9 @@ public class RenderFloatingItem extends RenderItem } } + @Override + public boolean shouldBob() + { + return false; + } } diff --git a/src/main/java/appeng/entity/RenderTinyTNTPrimed.java b/src/main/java/appeng/entity/RenderTinyTNTPrimed.java index 50ccfe049..874161254 100644 --- a/src/main/java/appeng/entity/RenderTinyTNTPrimed.java +++ b/src/main/java/appeng/entity/RenderTinyTNTPrimed.java @@ -18,6 +18,7 @@ package appeng.entity; + import org.lwjgl.opengl.GL11; import net.minecraft.client.renderer.RenderBlocks; @@ -31,33 +32,41 @@ import net.minecraft.util.ResourceLocation; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -@SideOnly(Side.CLIENT) + +@SideOnly( Side.CLIENT ) public class RenderTinyTNTPrimed extends Render { private final RenderBlocks blockRenderer = new RenderBlocks(); - public RenderTinyTNTPrimed() { + public RenderTinyTNTPrimed() + { this.shadowSize = 0.5F; this.renderManager = RenderManager.instance; } + @Override + public void doRender( Entity tnt, double x, double y, double z, float unused, float life ) + { + this.renderPrimedTNT( (EntityTinyTNTPrimed) tnt, x, y, z, life ); + } + public void renderPrimedTNT( EntityTinyTNTPrimed tnt, double x, double y, double z, float life ) { GL11.glPushMatrix(); GL11.glTranslatef( (float) x, (float) y - 0.25f, (float) z ); float f2; - if ( tnt.fuse - life + 1.0F < 10.0F ) + if( tnt.fuse - life + 1.0F < 10.0F ) { - f2 = 1.0F - (tnt.fuse - life + 1.0F) / 10.0F; + f2 = 1.0F - ( tnt.fuse - life + 1.0F ) / 10.0F; - if ( f2 < 0.0F ) + if( f2 < 0.0F ) { f2 = 0.0F; } - if ( f2 > 1.0F ) + if( f2 > 1.0F ) { f2 = 1.0F; } @@ -69,11 +78,11 @@ public class RenderTinyTNTPrimed extends Render } GL11.glScalef( 0.5f, 0.5f, 0.5f ); - f2 = (1.0F - (tnt.fuse - life + 1.0F) / 100.0F) * 0.8F; + f2 = ( 1.0F - ( tnt.fuse - life + 1.0F ) / 100.0F ) * 0.8F; this.bindEntityTexture( tnt ); this.blockRenderer.renderBlockAsItem( Blocks.tnt, 0, tnt.getBrightness( life ) ); - if ( tnt.fuse / 5 % 2 == 0 ) + if( tnt.fuse / 5 % 2 == 0 ) { GL11.glDisable( GL11.GL_TEXTURE_2D ); GL11.glDisable( GL11.GL_LIGHTING ); @@ -91,15 +100,8 @@ public class RenderTinyTNTPrimed extends Render } @Override - public void doRender(Entity tnt, double x, double y, double z, float unused, float life) - { - this.renderPrimedTNT( (EntityTinyTNTPrimed) tnt, x, y, z, life ); - } - - @Override - protected ResourceLocation getEntityTexture(Entity entity) + protected ResourceLocation getEntityTexture( Entity entity ) { return TextureMap.locationBlocksTexture; } - } diff --git a/src/main/java/appeng/facade/FacadeContainer.java b/src/main/java/appeng/facade/FacadeContainer.java index cb640b186..061c798d8 100644 --- a/src/main/java/appeng/facade/FacadeContainer.java +++ b/src/main/java/appeng/facade/FacadeContainer.java @@ -18,6 +18,7 @@ package appeng.facade; + import java.io.IOException; import io.netty.buffer.ByteBuf; @@ -38,72 +39,113 @@ import appeng.integration.abstraction.IBC; import appeng.items.parts.ItemFacade; import appeng.parts.CableBusStorage; + public class FacadeContainer implements IFacadeContainer { final int facades = 6; final CableBusStorage storage; - public FacadeContainer(CableBusStorage cbs) { + public FacadeContainer( CableBusStorage cbs ) + { this.storage = cbs; } @Override - public void writeToStream(ByteBuf out) throws IOException + public boolean addFacade( IFacadePart a ) { - int facadeSides = 0; - for (int x = 0; x < this.facades; x++) + if( this.getFacade( a.getSide() ) == null ) { - if ( this.getFacade( ForgeDirection.getOrientation( x ) ) != null ) - facadeSides |= ( 1 << x ); + this.storage.setFacade( a.getSide().ordinal(), a ); + return true; } - out.writeByte( (byte) facadeSides ); + return false; + } - for (int x = 0; x < this.facades; x++) + @Override + public void removeFacade( IPartHost host, ForgeDirection side ) + { + if( side != null && side != ForgeDirection.UNKNOWN ) { - IFacadePart part = this.getFacade( ForgeDirection.getOrientation( x ) ); - if ( part != null ) + if( this.storage.getFacade( side.ordinal() ) != null ) { - int itemID = Item.getIdFromItem( part.getItem() ); - int dmgValue = part.getItemDamage(); - out.writeInt( itemID * (part.isBC() ? -1 : 1) ); - out.writeInt( dmgValue ); + this.storage.setFacade( side.ordinal(), null ); + if( host != null ) + host.markForUpdate(); } } } @Override - public boolean readFromStream(ByteBuf out) throws IOException + public IFacadePart getFacade( ForgeDirection s ) + { + return this.storage.getFacade( s.ordinal() ); + } + + @Override + public void rotateLeft() + { + IFacadePart[] newFacades = new FacadePart[6]; + + newFacades[ForgeDirection.UP.ordinal()] = this.storage.getFacade( ForgeDirection.UP.ordinal() ); + newFacades[ForgeDirection.DOWN.ordinal()] = this.storage.getFacade( ForgeDirection.DOWN.ordinal() ); + + newFacades[ForgeDirection.EAST.ordinal()] = this.storage.getFacade( ForgeDirection.NORTH.ordinal() ); + newFacades[ForgeDirection.SOUTH.ordinal()] = this.storage.getFacade( ForgeDirection.EAST.ordinal() ); + + newFacades[ForgeDirection.WEST.ordinal()] = this.storage.getFacade( ForgeDirection.SOUTH.ordinal() ); + newFacades[ForgeDirection.NORTH.ordinal()] = this.storage.getFacade( ForgeDirection.WEST.ordinal() ); + + for( int x = 0; x < this.facades; x++ ) + this.storage.setFacade( x, newFacades[x] ); + } + + @Override + public void writeToNBT( NBTTagCompound c ) + { + for( int x = 0; x < this.facades; x++ ) + { + if( this.storage.getFacade( x ) != null ) + { + NBTTagCompound data = new NBTTagCompound(); + this.storage.getFacade( x ).getItemStack().writeToNBT( data ); + c.setTag( "facade:" + x, data ); + } + } + } + + @Override + public boolean readFromStream( ByteBuf out ) throws IOException { int facadeSides = out.readByte(); boolean changed = false; int[] ids = new int[2]; - for (int x = 0; x < this.facades; x++) + for( int x = 0; x < this.facades; x++ ) { ForgeDirection side = ForgeDirection.getOrientation( x ); - int ix = (1 << x); - if ( (facadeSides & ix) == ix ) + int ix = ( 1 << x ); + if( ( facadeSides & ix ) == ix ) { ids[0] = out.readInt(); ids[1] = out.readInt(); boolean isBC = ids[0] < 0; ids[0] = Math.abs( ids[0] ); - if ( isBC && AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) + if( isBC && AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) { IBC bc = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); changed = changed || this.storage.getFacade( x ) == null; this.storage.setFacade( x, bc.createFacadePart( (Block) Block.blockRegistry.getObjectById( ids[0] ), ids[1], side ) ); } - else if ( !isBC ) + else if( !isBC ) { - for ( Item facadeItem : AEApi.instance().definitions().items().facade().maybeItem().asSet() ) + for( Item facadeItem : AEApi.instance().definitions().items().facade().maybeItem().asSet() ) { ItemFacade ifa = (ItemFacade) facadeItem; ItemStack facade = ifa.createFromIDs( ids ); - if ( facade != null ) + if( facade != null ) { changed = changed || this.storage.getFacade( x ) == null; this.storage.setFacade( x, ifa.createPartFromItemStack( facade, side ) ); @@ -122,27 +164,27 @@ public class FacadeContainer implements IFacadeContainer } @Override - public void readFromNBT(NBTTagCompound c) + public void readFromNBT( NBTTagCompound c ) { - for (int x = 0; x < this.facades; x++) + for( int x = 0; x < this.facades; x++ ) { this.storage.setFacade( x, null ); NBTTagCompound t = c.getCompoundTag( "facade:" + x ); - if ( t != null ) + if( t != null ) { ItemStack is = ItemStack.loadItemStackFromNBT( t ); - if ( is != null ) + if( is != null ) { Item i = is.getItem(); - if ( i instanceof IFacadeItem ) - this.storage.setFacade( x, ((IFacadeItem) i).createPartFromItemStack( is, ForgeDirection.getOrientation( x ) ) ); + if( i instanceof IFacadeItem ) + this.storage.setFacade( x, ( (IFacadeItem) i ).createPartFromItemStack( is, ForgeDirection.getOrientation( x ) ) ); else { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) { IBC bc = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); - if ( bc.isFacade( is ) ) + if( bc.isFacade( is ) ) this.storage.setFacade( x, bc.createFacadePart( is, ForgeDirection.getOrientation( x ) ) ); } } @@ -152,74 +194,35 @@ public class FacadeContainer implements IFacadeContainer } @Override - public void writeToNBT(NBTTagCompound c) + public void writeToStream( ByteBuf out ) throws IOException { - for (int x = 0; x < this.facades; x++) + int facadeSides = 0; + for( int x = 0; x < this.facades; x++ ) { - if ( this.storage.getFacade( x ) != null ) + if( this.getFacade( ForgeDirection.getOrientation( x ) ) != null ) + facadeSides |= ( 1 << x ); + } + out.writeByte( (byte) facadeSides ); + + for( int x = 0; x < this.facades; x++ ) + { + IFacadePart part = this.getFacade( ForgeDirection.getOrientation( x ) ); + if( part != null ) { - NBTTagCompound data = new NBTTagCompound(); - this.storage.getFacade( x ).getItemStack().writeToNBT( data ); - c.setTag( "facade:" + x, data ); + int itemID = Item.getIdFromItem( part.getItem() ); + int dmgValue = part.getItemDamage(); + out.writeInt( itemID * ( part.isBC() ? -1 : 1 ) ); + out.writeInt( dmgValue ); } } } - @Override - public boolean addFacade(IFacadePart a) - { - if ( this.getFacade( a.getSide() ) == null ) - { - this.storage.setFacade( a.getSide().ordinal(), a ); - return true; - } - return false; - } - - @Override - public void removeFacade(IPartHost host, ForgeDirection side) - { - if ( side != null && side != ForgeDirection.UNKNOWN ) - { - if ( this.storage.getFacade( side.ordinal() ) != null ) - { - this.storage.setFacade( side.ordinal(), null ); - if ( host != null ) - host.markForUpdate(); - } - } - } - - @Override - public IFacadePart getFacade(ForgeDirection s) - { - return this.storage.getFacade( s.ordinal() ); - } - @Override public boolean isEmpty() { - for (int x = 0; x < this.facades; x++) - if ( this.storage.getFacade( x ) != null ) + for( int x = 0; x < this.facades; x++ ) + if( this.storage.getFacade( x ) != null ) return false; return true; } - - @Override - public void rotateLeft() - { - IFacadePart[] newFacades = new FacadePart[6]; - - newFacades[ForgeDirection.UP.ordinal()] = this.storage.getFacade( ForgeDirection.UP.ordinal() ); - newFacades[ForgeDirection.DOWN.ordinal()] = this.storage.getFacade( ForgeDirection.DOWN.ordinal() ); - - newFacades[ForgeDirection.EAST.ordinal()] = this.storage.getFacade( ForgeDirection.NORTH.ordinal() ); - newFacades[ForgeDirection.SOUTH.ordinal()] = this.storage.getFacade( ForgeDirection.EAST.ordinal() ); - - newFacades[ForgeDirection.WEST.ordinal()] = this.storage.getFacade( ForgeDirection.SOUTH.ordinal() ); - newFacades[ForgeDirection.NORTH.ordinal()] = this.storage.getFacade( ForgeDirection.WEST.ordinal() ); - - for (int x = 0; x < this.facades; x++) - this.storage.setFacade( x, newFacades[x] ); - } } diff --git a/src/main/java/appeng/facade/FacadePart.java b/src/main/java/appeng/facade/FacadePart.java index cff1703e9..a8ba504d2 100644 --- a/src/main/java/appeng/facade/FacadePart.java +++ b/src/main/java/appeng/facade/FacadePart.java @@ -18,6 +18,7 @@ package appeng.facade; + import java.util.EnumSet; import org.lwjgl.opengl.GL11; @@ -55,6 +56,7 @@ import appeng.integration.IntegrationType; import appeng.integration.abstraction.IBC; import appeng.util.Platform; + public class FacadePart implements IFacadePart, IBoxProvider { @@ -62,17 +64,23 @@ public class FacadePart implements IFacadePart, IBoxProvider public final ForgeDirection side; public int thickness = 2; - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) ISimplifiedBundle prevLight; - public FacadePart(ItemStack facade, ForgeDirection side) { - if ( facade == null ) + public FacadePart( ItemStack facade, ForgeDirection side ) + { + if( facade == null ) throw new RuntimeException( "Facade Part constructed on null item." ); this.facade = facade.copy(); this.facade.stackSize = 1; this.side = side; } + public static boolean isFacade( ItemStack is ) + { + return is.getItem() instanceof IFacadeItem; + } + @Override public ItemStack getItemStack() { @@ -80,9 +88,9 @@ public class FacadePart implements IFacadePart, IBoxProvider } @Override - public void getBoxes(IPartCollisionHelper ch, Entity e) + public void getBoxes( IPartCollisionHelper ch, Entity e ) { - if ( e instanceof EntityLivingBase ) + if( e instanceof EntityLivingBase ) { // prevent weird snag behavior ch.addBox( 0.0, 0.0, 14, 16.0, 16.0, 16.0 ); @@ -95,103 +103,68 @@ public class FacadePart implements IFacadePart, IBoxProvider } @Override - public void getBoxes(IPartCollisionHelper bch) + @SideOnly( Side.CLIENT ) + public void renderStatic( int x, int y, int z, IPartRenderHelper instance2, RenderBlocks renderer, IFacadeContainer fc, AxisAlignedBB busBounds, boolean renderStilt ) { - this.getBoxes( bch, null ); - - } - - public static boolean isFacade(ItemStack is) - { - return is.getItem() instanceof IFacadeItem; - } - - ItemStack getTexture() - { - final Item maybeFacade = this.facade.getItem(); - - // AE Facade - if ( maybeFacade instanceof IFacadeItem ) - { - IFacadeItem facade = (IFacadeItem) maybeFacade; - - return facade.getTextureItem( this.facade ); - } - else if ( AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) - { - IBC bc = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); - - return bc.getTextureForFacade( this.facade ); - } - - return null; - } - - @Override - @SideOnly(Side.CLIENT) - public void renderStatic(int x, int y, int z, IPartRenderHelper instance2, RenderBlocks renderer, IFacadeContainer fc, AxisAlignedBB busBounds, - boolean renderStilt) - { - if ( this.facade != null ) + if( this.facade != null ) { BusRenderHelper instance = (BusRenderHelper) instance2; try - { + { ItemStack randomItem = this.getTexture(); RenderBlocksWorkaround rbw = null; - if ( renderer instanceof RenderBlocksWorkaround ) + if( renderer instanceof RenderBlocksWorkaround ) { rbw = (RenderBlocksWorkaround) renderer; } - if ( renderStilt && busBounds == null ) + if( renderStilt && busBounds == null ) { - if ( rbw != null ) + if( rbw != null ) { rbw.isFacade = false; rbw.calculations = true; } IIcon myIcon = null; - if ( this.isBC() ) + if( this.isBC() ) { IBC bc = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); myIcon = bc.getFacadeTexture(); } - if ( myIcon == null ) + if( myIcon == null ) myIcon = this.facade.getIconIndex(); instance.setTexture( myIcon ); - if ( this.isBC() ) + if( this.isBC() ) instance.setBounds( 6, 6, 10, 10, 10, 15 ); else instance.setBounds( 7, 7, 10, 9, 9, 15 ); instance.renderBlock( x, y, z, renderer ); instance.setTexture( null ); - } - if ( randomItem != null ) + if( randomItem != null ) { - if ( randomItem.getItem() instanceof ItemBlock ) + if( randomItem.getItem() instanceof ItemBlock ) { ItemBlock ib = (ItemBlock) randomItem.getItem(); Block blk = Block.getBlockFromItem( ib ); - if ( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) + if( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) { - if ( rbw != null ) + if( rbw != null ) rbw.opacity = 0.3f; instance.renderForPass( 1 ); } else { - if ( blk.canRenderInPass( 1 ) ) + if( blk.canRenderInPass( 1 ) ) { instance.renderForPass( 1 ); } @@ -203,7 +176,7 @@ public class FacadePart implements IFacadePart, IBoxProvider { color = ib.getColorFromItemStack( randomItem, 0 ); } - catch (Throwable ignored) + catch( Throwable ignored ) { } @@ -211,14 +184,14 @@ public class FacadePart implements IFacadePart, IBoxProvider instance.setBounds( 0, 0, 16 - this.thickness, 16, 16, 16 ); instance.prepareBounds( renderer ); - if ( rbw != null ) + if( rbw != null ) { rbw.isFacade = true; rbw.calculations = true; rbw.faces = EnumSet.noneOf( ForgeDirection.class ); - if ( this.prevLight != null && rbw.similarLighting( blk, rbw.blockAccess, x, y, z, this.prevLight ) ) + if( this.prevLight != null && rbw.similarLighting( blk, rbw.blockAccess, x, y, z, this.prevLight ) ) rbw.populate( this.prevLight ); else { @@ -231,38 +204,27 @@ public class FacadePart implements IFacadePart, IBoxProvider rbw.calculations = false; rbw.faces = this.calculateFaceOpenFaces( rbw.blockAccess, fc, x, y, z, this.side ); - ((RenderBlocksWorkaround) renderer).setTexture( - blk.getIcon( ForgeDirection.DOWN.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.UP.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.NORTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.SOUTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.WEST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.EAST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ) ); + ( (RenderBlocksWorkaround) renderer ).setTexture( blk.getIcon( ForgeDirection.DOWN.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.UP.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.NORTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.SOUTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.WEST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.EAST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ) ); } else { - instance.setTexture( blk.getIcon( ForgeDirection.DOWN.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.UP.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.NORTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.SOUTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.WEST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), - blk.getIcon( ForgeDirection.EAST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ) ); + instance.setTexture( blk.getIcon( ForgeDirection.DOWN.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.UP.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.NORTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.SOUTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.WEST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.EAST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ) ); } - if ( busBounds == null ) + if( busBounds == null ) { - if ( this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN ) + if( this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN ) { instance.renderBlockCurrentBounds( x, y, z, renderer ); } - else if ( this.side == ForgeDirection.NORTH || this.side == ForgeDirection.SOUTH ) + else if( this.side == ForgeDirection.NORTH || this.side == ForgeDirection.SOUTH ) { - if ( fc.getFacade( ForgeDirection.UP ) != null ) + if( fc.getFacade( ForgeDirection.UP ) != null ) { renderer.renderMaxY -= this.thickness / 16.0; } - if ( fc.getFacade( ForgeDirection.DOWN ) != null ) + if( fc.getFacade( ForgeDirection.DOWN ) != null ) { renderer.renderMinY += this.thickness / 16.0; } @@ -271,22 +233,22 @@ public class FacadePart implements IFacadePart, IBoxProvider } else { - if ( fc.getFacade( ForgeDirection.UP ) != null ) + if( fc.getFacade( ForgeDirection.UP ) != null ) { renderer.renderMaxY -= this.thickness / 16.0; } - if ( fc.getFacade( ForgeDirection.DOWN ) != null ) + if( fc.getFacade( ForgeDirection.DOWN ) != null ) { renderer.renderMinY += this.thickness / 16.0; } - if ( fc.getFacade( ForgeDirection.SOUTH ) != null ) + if( fc.getFacade( ForgeDirection.SOUTH ) != null ) { renderer.renderMaxZ -= this.thickness / 16.0; } - if ( fc.getFacade( ForgeDirection.NORTH ) != null ) + if( fc.getFacade( ForgeDirection.NORTH ) != null ) { renderer.renderMinZ += this.thickness / 16.0; } @@ -296,21 +258,21 @@ public class FacadePart implements IFacadePart, IBoxProvider } else { - if ( this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN ) + if( this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN ) { this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, busBounds.maxZ, 1.0, 1.0, 1.0 ); this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, 0.0, 1.0, 1.0, busBounds.minZ ); this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, busBounds.minZ, busBounds.minX, 1.0, busBounds.maxZ ); this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, busBounds.maxX, 0.0, busBounds.minZ, 1.0, 1.0, busBounds.maxZ ); } - else if ( this.side == ForgeDirection.NORTH || this.side == ForgeDirection.SOUTH ) + else if( this.side == ForgeDirection.NORTH || this.side == ForgeDirection.SOUTH ) { - if ( fc.getFacade( ForgeDirection.UP ) != null ) + if( fc.getFacade( ForgeDirection.UP ) != null ) { renderer.renderMaxY -= this.thickness / 16.0; } - if ( fc.getFacade( ForgeDirection.DOWN ) != null ) + if( fc.getFacade( ForgeDirection.DOWN ) != null ) { renderer.renderMinY += this.thickness / 16.0; } @@ -322,22 +284,22 @@ public class FacadePart implements IFacadePart, IBoxProvider } else { - if ( fc.getFacade( ForgeDirection.UP ) != null ) + if( fc.getFacade( ForgeDirection.UP ) != null ) { renderer.renderMaxY -= this.thickness / 16.0; } - if ( fc.getFacade( ForgeDirection.DOWN ) != null ) + if( fc.getFacade( ForgeDirection.DOWN ) != null ) { renderer.renderMinY += this.thickness / 16.0; } - if ( fc.getFacade( ForgeDirection.SOUTH ) != null ) + if( fc.getFacade( ForgeDirection.SOUTH ) != null ) { renderer.renderMaxZ -= this.thickness / 16.0; } - if ( fc.getFacade( ForgeDirection.NORTH ) != null ) + if( fc.getFacade( ForgeDirection.NORTH ) != null ) { renderer.renderMinZ += this.thickness / 16.0; } @@ -349,7 +311,7 @@ public class FacadePart implements IFacadePart, IBoxProvider } } - if ( rbw != null ) + if( rbw != null ) { rbw.opacity = 1.0f; rbw.faces = EnumSet.allOf( ForgeDirection.class ); @@ -361,52 +323,72 @@ public class FacadePart implements IFacadePart, IBoxProvider } } } - catch (Throwable t) + catch( Throwable t ) { AELog.error( t ); - } } } - private EnumSet calculateFaceOpenFaces(IBlockAccess blockAccess, IFacadeContainer fc, int x, int y, int z, ForgeDirection side) + ItemStack getTexture() + { + final Item maybeFacade = this.facade.getItem(); + + // AE Facade + if( maybeFacade instanceof IFacadeItem ) + { + IFacadeItem facade = (IFacadeItem) maybeFacade; + + return facade.getTextureItem( this.facade ); + } + else if( AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) + { + IBC bc = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); + + return bc.getTextureForFacade( this.facade ); + } + + return null; + } + + private EnumSet calculateFaceOpenFaces( IBlockAccess blockAccess, IFacadeContainer fc, int x, int y, int z, ForgeDirection side ) { EnumSet out = EnumSet.of( side, side.getOpposite() ); IFacadePart facade = fc.getFacade( side ); - for (ForgeDirection it : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection it : ForgeDirection.VALID_DIRECTIONS ) { - if ( !out.contains( it ) && this.hasAlphaDiff( blockAccess.getTileEntity( x + it.offsetX, y + it.offsetY, z + it.offsetZ ), side, facade ) ) + if( !out.contains( it ) && this.hasAlphaDiff( blockAccess.getTileEntity( x + it.offsetX, y + it.offsetY, z + it.offsetZ ), side, facade ) ) { out.add( it ); } } - if ( out.contains( ForgeDirection.UP ) && (side.offsetX != 0 || side.offsetZ != 0) ) + if( out.contains( ForgeDirection.UP ) && ( side.offsetX != 0 || side.offsetZ != 0 ) ) { IFacadePart fp = fc.getFacade( ForgeDirection.UP ); - if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) + if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) out.remove( ForgeDirection.UP ); } - if ( out.contains( ForgeDirection.DOWN ) && (side.offsetX != 0 || side.offsetZ != 0) ) + if( out.contains( ForgeDirection.DOWN ) && ( side.offsetX != 0 || side.offsetZ != 0 ) ) { IFacadePart fp = fc.getFacade( ForgeDirection.DOWN ); - if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) + if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) out.remove( ForgeDirection.DOWN ); } - if ( out.contains( ForgeDirection.SOUTH ) && (side.offsetX != 0) ) + if( out.contains( ForgeDirection.SOUTH ) && ( side.offsetX != 0 ) ) { IFacadePart fp = fc.getFacade( ForgeDirection.SOUTH ); - if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) + if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) out.remove( ForgeDirection.SOUTH ); } - if ( out.contains( ForgeDirection.NORTH ) && (side.offsetX != 0) ) + if( out.contains( ForgeDirection.NORTH ) && ( side.offsetX != 0 ) ) { IFacadePart fp = fc.getFacade( ForgeDirection.NORTH ); - if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) + if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) out.remove( ForgeDirection.NORTH ); } @@ -438,22 +420,8 @@ public class FacadePart implements IFacadePart, IBoxProvider return out; } - private boolean hasAlphaDiff( TileEntity tileEntity, ForgeDirection side, IFacadePart facade ) - { - if ( tileEntity instanceof IPartHost ) - { - IPartHost ph = (IPartHost) tileEntity; - IFacadePart fp = ph.getFacadeContainer().getFacade( side ); - - return fp == null || (fp.isTransparent() != facade.isTransparent()); - } - - return true; - } - - @SideOnly(Side.CLIENT) - private void renderSegmentBlockCurrentBounds(IPartRenderHelper instance, int x, int y, int z, RenderBlocks renderer, double minX, double minY, double minZ, - double maxX, double maxY, double maxZ) + @SideOnly( Side.CLIENT ) + private void renderSegmentBlockCurrentBounds( IPartRenderHelper instance, int x, int y, int z, RenderBlocks renderer, double minX, double minY, double minZ, double maxX, double maxY, double maxZ ) { double oldMinX = renderer.renderMinX; double oldMinY = renderer.renderMinY; @@ -470,8 +438,7 @@ public class FacadePart implements IFacadePart, IBoxProvider renderer.renderMaxZ = Math.min( renderer.renderMaxZ, maxZ ); // don't draw it if its not at least a pixel wide... - if ( renderer.renderMaxX - renderer.renderMinX >= 1.0 / 16.0 && renderer.renderMaxY - renderer.renderMinY >= 1.0 / 16.0 - && renderer.renderMaxZ - renderer.renderMinZ >= 1.0 / 16.0 ) + if( renderer.renderMaxX - renderer.renderMinX >= 1.0 / 16.0 && renderer.renderMaxY - renderer.renderMinY >= 1.0 / 16.0 && renderer.renderMaxZ - renderer.renderMinZ >= 1.0 / 16.0 ) { instance.renderBlockCurrentBounds( x, y, z, renderer ); } @@ -484,11 +451,24 @@ public class FacadePart implements IFacadePart, IBoxProvider renderer.renderMaxZ = oldMaxZ; } - @Override - @SideOnly(Side.CLIENT) - public void renderInventory(IPartRenderHelper instance, RenderBlocks renderer) + private boolean hasAlphaDiff( TileEntity tileEntity, ForgeDirection side, IFacadePart facade ) { - if ( this.facade != null ) + if( tileEntity instanceof IPartHost ) + { + IPartHost ph = (IPartHost) tileEntity; + IFacadePart fp = ph.getFacadeContainer().getFacade( side ); + + return fp == null || ( fp.isTransparent() != facade.isTransparent() ); + } + + return true; + } + + @Override + @SideOnly( Side.CLIENT ) + public void renderInventory( IPartRenderHelper instance, RenderBlocks renderer ) + { + if( this.facade != null ) { IFacadeItem fi = (IFacadeItem) this.facade.getItem(); @@ -501,9 +481,9 @@ public class FacadePart implements IFacadePart, IBoxProvider instance.renderInventoryBox( renderer ); instance.setTexture( null ); - if ( randomItem != null ) + if( randomItem != null ) { - if ( randomItem.getItem() instanceof ItemBlock ) + if( randomItem.getItem() instanceof ItemBlock ) { ItemBlock ib = (ItemBlock) randomItem.getItem(); Block blk = Block.getBlockFromItem( ib ); @@ -514,7 +494,7 @@ public class FacadePart implements IFacadePart, IBoxProvider GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0F ); instance.setInvColor( color ); } - catch (Throwable error) + catch( Throwable error ) { GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0F ); instance.setInvColor( 0xffffff ); @@ -531,7 +511,7 @@ public class FacadePart implements IFacadePart, IBoxProvider } } } - catch (Throwable ignored) + catch( Throwable ignored ) { } @@ -554,7 +534,7 @@ public class FacadePart implements IFacadePart, IBoxProvider public Item getItem() { ItemStack is = this.getTexture(); - if ( is == null ) + if( is == null ) return null; return is.getItem(); } @@ -563,7 +543,7 @@ public class FacadePart implements IFacadePart, IBoxProvider public int getItemDamage() { ItemStack is = this.getTexture(); - if ( is == null ) + if( is == null ) return 0; return is.getItemDamage(); } @@ -571,11 +551,11 @@ public class FacadePart implements IFacadePart, IBoxProvider @Override public boolean isBC() { - return !( this.facade.getItem() instanceof IFacadeItem); + return !( this.facade.getItem() instanceof IFacadeItem ); } @Override - public void setThinFacades(boolean useThinFacades) + public void setThinFacades( boolean useThinFacades ) { this.thickness = useThinFacades ? 1 : 2; } @@ -583,7 +563,7 @@ public class FacadePart implements IFacadePart, IBoxProvider @Override public boolean isTransparent() { - if ( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) + if( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) return true; ItemStack is = this.getTexture(); @@ -592,4 +572,9 @@ public class FacadePart implements IFacadePart, IBoxProvider return !blk.isOpaqueCube(); } + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + this.getBoxes( bch, null ); + } } diff --git a/src/main/java/appeng/facade/IFacadeItem.java b/src/main/java/appeng/facade/IFacadeItem.java index 7b3da65fc..39c4baede 100644 --- a/src/main/java/appeng/facade/IFacadeItem.java +++ b/src/main/java/appeng/facade/IFacadeItem.java @@ -18,19 +18,20 @@ package appeng.facade; + import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; + public interface IFacadeItem { - FacadePart createPartFromItemStack(ItemStack is, ForgeDirection side); + FacadePart createPartFromItemStack( ItemStack is, ForgeDirection side ); - ItemStack getTextureItem(ItemStack is); + ItemStack getTextureItem( ItemStack is ); - int getMeta(ItemStack is); - - Block getBlock(ItemStack is); + int getMeta( ItemStack is ); + Block getBlock( ItemStack is ); } diff --git a/src/main/java/appeng/fmp/CableBusPart.java b/src/main/java/appeng/fmp/CableBusPart.java index 61e89e679..e1d356443 100644 --- a/src/main/java/appeng/fmp/CableBusPart.java +++ b/src/main/java/appeng/fmp/CableBusPart.java @@ -18,6 +18,7 @@ package appeng.fmp; + import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; @@ -76,6 +77,7 @@ import appeng.parts.PartPlacement; import appeng.tile.networking.TileCableBus; import appeng.util.Platform; + /** * Implementing these might help improve visuals for hollow covers * @@ -84,6 +86,7 @@ import appeng.util.Platform; public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IRedstonePart, AEMultiTile { + public static final ThreadLocal DISABLE_FACADE_OCCLUSION = new ThreadLocal(); private final static Cuboid6[] SIDE_TESTS = new Cuboid6[] { new Cuboid6( 6.0 / 16.0, 0, 6.0 / 16.0, 10.0 / 16.0, 6.0 / 16.0, 10.0 / 16.0 ), // DOWN(0, -1, 0), @@ -98,99 +101,23 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds new Cuboid6( 10.0 / 16.0, 6.0 / 16.0, 6.0 / 16.0, 1.0, 10.0 / 16.0, 10.0 / 16.0 ),// EAST(1, 0, 0), }; - - public static final ThreadLocal DISABLE_FACADE_OCCLUSION = new ThreadLocal(); public CableBusContainer cb = new CableBusContainer( this ); + boolean canUpdate = false; @Override - public boolean isInWorld() - { - return this.cb.isInWorld(); - } - - @Override - public boolean doesTick() - { - return false; - } - - @Override - public AECableType getCableConnectionType(ForgeDirection dir) - { - return this.cb.getCableConnectionType( dir ); - } - - @Override - public boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who) + public boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ) { return this.cb.recolourBlock( side, colour, who ); } - @Override - public AEColor getColor() - { - return this.cb.getColor(); - } - - @Override - public void save(NBTTagCompound tag) - { - this.cb.writeToNBT( tag ); - } - - @Override - public void load(NBTTagCompound tag) - { - this.cb.readFromNBT( tag ); - } - - @Override - public void writeDesc(MCDataOutput packet) - { - ByteBuf stream = Unpooled.buffer(); - - try - { - this.cb.writeToStream( stream ); - packet.writeInt( stream.readableBytes() ); - stream.capacity( stream.readableBytes() ); - packet.writeByteArray( stream.array() ); - } - catch (IOException e) - { - AELog.error( e ); - } - - } - - @Override - public void readDesc(MCDataInput packet) - { - int len = packet.readInt(); - byte[] data = packet.readByteArray( len ); - - try - { - if ( len > 0 ) - { - ByteBuf byteBuffer = Unpooled.wrappedBuffer( data ); - this.cb.readFromStream( byteBuffer ); - } - } - catch (IOException e) - { - AELog.error( e ); - } - } - @Override public Cuboid6 getBounds() { AxisAlignedBB b = null; - for (AxisAlignedBB bx : this.cb.getSelectedBoundingBoxesFromPool( false, true, null, true )) + for( AxisAlignedBB bx : this.cb.getSelectedBoundingBoxesFromPool( false, true, null, true ) ) { - if ( b == null ) + if( b == null ) b = bx; else { @@ -204,7 +131,7 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds } } - if ( b == null ) + if( b == null ) return new Cuboid6( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ); return new Cuboid6( b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ ); @@ -217,36 +144,9 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds } @Override - public void onPartChanged(TMultiPart part) + public int getLightValue() { - this.cb.updateConnections(); - } - - @Override - public ItemStack pickItem(MovingObjectPosition hit) - { - Vec3 v3 = hit.hitVec.addVector( -hit.blockX, -hit.blockY, -hit.blockZ ); - SelectedPart sp = this.cb.selectPart( v3 ); - if ( sp != null ) - { - if ( sp.part != null ) - return sp.part.getItemStack( PartItemStack.Break ); - if ( sp.facade != null ) - return sp.facade.getItemStack(); - } - return null; - } - - @Override - public Iterable getDrops() - { - return this.cb.getDrops( new ArrayList() ); - } - - @Override - public void onEntityCollision(Entity entity) - { - this.cb.onEntityCollision( entity ); + return this.cb.getLightValue(); } @Override @@ -258,56 +158,15 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds } @Override - public void onWorldSeparate() + public boolean occlusionTest( TMultiPart part ) { - this.canUpdate = false; - this.cb.removeFromWorld(); + return NormalOcclusionTest.apply( this, part ); } @Override - public boolean canConnectRedstone(int side) + public boolean renderStatic( Vector3 pos, int pass ) { - return this.cb.canConnectRedstone( EnumSet.of( ForgeDirection.getOrientation( side ) ) ); - } - - @Override - public int strongPowerLevel(int side) - { - return this.cb.isProvidingStrongPower( ForgeDirection.getOrientation( side ) ); - } - - @Override - public int weakPowerLevel(int side) - { - return this.cb.isProvidingWeakPower( ForgeDirection.getOrientation( side ) ); - } - - @Override - public void onNeighborChanged() - { - this.cb.onNeighborChanged(); - } - - @Override - public boolean activate(EntityPlayer player, MovingObjectPosition hit, ItemStack item) - { - return this.cb.activate( player, hit.hitVec.addVector( -hit.blockX, -hit.blockY, -hit.blockZ ) ); - } - - @Override - public void renderDynamic(Vector3 pos, float frame, int pass) - { - if ( pass == 0 || (pass == 1 && AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass )) ) - { - BusRenderHelper.INSTANCE.setPass( pass ); - this.cb.renderDynamic( pos.x, pos.y, pos.z ); - } - } - - @Override - public boolean renderStatic(Vector3 pos, int pass) - { - if ( pass == 0 || (pass == 1 && AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass )) ) + if( pass == 0 || ( pass == 1 && AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) ) { BusRenderHelper.INSTANCE.setPass( pass ); BusRenderer.INSTANCE.renderer.renderAllFaces = true; @@ -320,93 +179,101 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds } @Override - public int getLightValue() + public void renderDynamic( Vector3 pos, float frame, int pass ) { - return this.cb.getLightValue(); - } - - @Override - public boolean canAddPart(ItemStack is, ForgeDirection side) - { - IFacadePart fp = PartPlacement.isFacade( is, side ); - if ( fp != null ) + if( pass == 0 || ( pass == 1 && AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) ) { - if ( !(side == null || side == ForgeDirection.UNKNOWN || this.tile() == null) ) - { - List boxes = new ArrayList(); - IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - fp.getBoxes( bch, null ); - for (AxisAlignedBB bb : boxes) - { - DISABLE_FACADE_OCCLUSION.set( true ); - boolean canAdd = this.tile().canAddPart( new NormallyOccludedPart( new Cuboid6( bb ) ) ); - DISABLE_FACADE_OCCLUSION.remove(); - if ( !canAdd ) - { - return false; - } - } - } - return true; + BusRenderHelper.INSTANCE.setPass( pass ); + this.cb.renderDynamic( pos.x, pos.y, pos.z ); } + } - if ( is.getItem() instanceof IPartItem ) + @Override + public void onPartChanged( TMultiPart part ) + { + this.cb.updateConnections(); + } + + @Override + public void onEntityCollision( Entity entity ) + { + this.cb.onEntityCollision( entity ); + } + + @Override + public boolean activate( EntityPlayer player, MovingObjectPosition hit, ItemStack item ) + { + return this.cb.activate( player, hit.hitVec.addVector( -hit.blockX, -hit.blockY, -hit.blockZ ) ); + } + + @Override + public void load( NBTTagCompound tag ) + { + this.cb.readFromNBT( tag ); + } + + @Override + public void onWorldSeparate() + { + this.canUpdate = false; + this.cb.removeFromWorld(); + } + + @Override + public void save( NBTTagCompound tag ) + { + this.cb.writeToNBT( tag ); + } + + @Override + public void writeDesc( MCDataOutput packet ) + { + ByteBuf stream = Unpooled.buffer(); + + try { - IPartItem bi = (IPartItem) is.getItem(); - - is = is.copy(); - is.stackSize = 1; - - IPart bp = bi.createPartFromItemStack( is ); - if ( !(side == null || side == ForgeDirection.UNKNOWN || this.tile() == null) ) - { - List boxes = new ArrayList(); - IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - bp.getBoxes( bch ); - for (AxisAlignedBB bb : boxes) - { - if ( !this.tile().canAddPart( new NormallyOccludedPart( new Cuboid6( bb ) ) ) ) - { - return false; - } - } - } + this.cb.writeToStream( stream ); + packet.writeInt( stream.readableBytes() ); + stream.capacity( stream.readableBytes() ); + packet.writeByteArray( stream.array() ); + } + catch( IOException e ) + { + AELog.error( e ); } - - return this.cb.canAddPart( is, side ); } @Override - public ForgeDirection addPart(ItemStack is, ForgeDirection side, EntityPlayer owner) + public ItemStack pickItem( MovingObjectPosition hit ) { - return this.cb.addPart( is, side, owner ); + Vec3 v3 = hit.hitVec.addVector( -hit.blockX, -hit.blockY, -hit.blockZ ); + SelectedPart sp = this.cb.selectPart( v3 ); + if( sp != null ) + { + if( sp.part != null ) + return sp.part.getItemStack( PartItemStack.Break ); + if( sp.facade != null ) + return sp.facade.getItemStack(); + } + return null; } @Override - public IPart getPart(ForgeDirection side) + public Iterable getDrops() { - return this.cb.getPart( side ); + return this.cb.getDrops( new ArrayList() ); } @Override - public void removePart(ForgeDirection side, boolean suppressUpdate) + public void onNeighborChanged() { - this.cb.removePart( side, suppressUpdate ); - } - - boolean canUpdate = false; - - @Override - public void markForUpdate() - { - if ( Platform.isServer() && this.canUpdate ) - this.sendDescUpdate(); + this.cb.onNeighborChanged(); } @Override - public DimensionalCoord getLocation() + public boolean doesTick() { - return new DimensionalCoord( this.tile() ); + return false; } @Override @@ -415,46 +282,55 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds this.cb.setHost( this ); } - public void convertFromTile(TileEntity blockTileEntity) + @Override + public void readDesc( MCDataInput packet ) + { + int len = packet.readInt(); + byte[] data = packet.readByteArray( len ); + + try + { + if( len > 0 ) + { + ByteBuf byteBuffer = Unpooled.wrappedBuffer( data ); + this.cb.readFromStream( byteBuffer ); + } + } + catch( IOException e ) + { + AELog.error( e ); + } + } + + @Override + public boolean canConnectRedstone( int side ) + { + return this.cb.canConnectRedstone( EnumSet.of( ForgeDirection.getOrientation( side ) ) ); + } + + @Override + public int weakPowerLevel( int side ) + { + return this.cb.isProvidingWeakPower( ForgeDirection.getOrientation( side ) ); + } + + @Override + public int strongPowerLevel( int side ) + { + return this.cb.isProvidingStrongPower( ForgeDirection.getOrientation( side ) ); + } + + public void convertFromTile( TileEntity blockTileEntity ) { TileCableBus tcb = (TileCableBus) blockTileEntity; this.cb = tcb.cb; } - @Override - public boolean occlusionTest(TMultiPart part) - { - return NormalOcclusionTest.apply( this, part ); - } - - @Override - public Iterable getCollisionBoxes() - { - LinkedList l = new LinkedList(); - for (AxisAlignedBB b : this.cb.getSelectedBoundingBoxesFromPool( false, true, null, true )) - { - l.add( new Cuboid6( b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ ) ); - } - return l; - - } - - @Override - public Iterable getSubParts() - { - LinkedList l = new LinkedList(); - for (Cuboid6 c : this.getCollisionBoxes()) - { - l.add( new IndexedCuboid6( 0, c ) ); - } - return l; - } - @Override public Iterable getOcclusionBoxes() { LinkedList l = new LinkedList(); - for (AxisAlignedBB b : this.cb.getSelectedBoundingBoxesFromPool( true, DISABLE_FACADE_OCCLUSION.get() == null, null, true )) + for( AxisAlignedBB b : this.cb.getSelectedBoundingBoxesFromPool( true, DISABLE_FACADE_OCCLUSION.get() == null, null, true ) ) { l.add( new Cuboid6( b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ ) ); } @@ -462,68 +338,15 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds } @Override - public IGridNode getGridNode(ForgeDirection dir) + public IGridNode getGridNode( ForgeDirection dir ) { return this.cb.getGridNode( dir ); } @Override - public IFacadeContainer getFacadeContainer() + public AECableType getCableConnectionType( ForgeDirection dir ) { - return this.cb.getFacadeContainer(); - } - - @Override - public void clearContainer() - { - this.cb = new CableBusContainer( this ); - } - - @Override - public boolean isBlocked(ForgeDirection side) - { - if ( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) - return false; - - DISABLE_FACADE_OCCLUSION.set( true ); - boolean blocked = !this.tile().canAddPart( new NormallyOccludedPart( SIDE_TESTS[side.ordinal()] ) ); - DISABLE_FACADE_OCCLUSION.remove(); - - return blocked; - } - - @Override - public SelectedPart selectPart(Vec3 pos) - { - return this.cb.selectPart( pos ); - } - - @Override - public void partChanged() - { - if ( this.isInWorld() ) - this.notifyNeighbors(); - } - - @Override - public Set getLayerFlags() - { - return this.cb.getLayerFlags(); - } - - @Override - public void markForSave() - { - // mark the chunk for save... - TileEntity te = this.tile(); - if ( te != null && te.getWorldObj() != null ) - te.getWorldObj().getChunkFromBlockCoords( this.x(), this.z() ).isModified = true; - } - - @Override - public boolean hasRedstone(ForgeDirection side) - { - return this.cb.hasRedstone( side ); + return this.cb.getCableConnectionType( dir ); } @Override @@ -532,56 +355,34 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds this.cb.securityBreak(); } - @Override - public boolean isEmpty() - { - return this.cb.isEmpty(); - } - - @Override - public void cleanup() - { - this.tile().remPart( this ); - } - - @Override - public void notifyNeighbors() - { - if ( this.tile() instanceof TIInventoryTile ) - ((TIInventoryTile) this.tile()).rebuildSlotMap(); - - if ( this.world() != null && this.world().blockExists( this.x(), this.y(), this.z() ) && !CableBusContainer.isLoading() ) - Platform.notifyBlocksOfNeighbors(this.world(), this.x(), this.y(), this.z() ); - } - // @Override - public int getHollowSize(int side) + public int getHollowSize( int side ) { IPartCable cable = (IPartCable) this.getPart( ForgeDirection.UNKNOWN ); ForgeDirection dir = ForgeDirection.getOrientation( side ); - if ( cable != null && cable.isConnected( dir ) ) + if( cable != null && cable.isConnected( dir ) ) { List boxes = new ArrayList(); BusCollisionHelper bch = new BusCollisionHelper( boxes, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH, null, true ); - for (ForgeDirection whichSide : ForgeDirection.values()) + for( ForgeDirection whichSide : ForgeDirection.values() ) { IPart fPart = this.getPart( whichSide ); - if ( fPart != null ) + if( fPart != null ) fPart.getBoxes( bch ); } AxisAlignedBB b = null; AxisAlignedBB pb = Platform.getPrimaryBox( dir, 2 ); - for (AxisAlignedBB bb : boxes) + for( AxisAlignedBB bb : boxes ) { - if ( bb.intersectsWith( pb ) ) + if( bb.intersectsWith( pb ) ) { - if ( b == null ) + if( b == null ) b = bb; else { @@ -595,33 +396,33 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds } } - if ( b == null ) + if( b == null ) return 0; - switch (dir) + switch( dir ) { - case WEST: - case EAST: - return this.getSize( b.minZ, b.maxZ, b.minY, b.maxY ); - case DOWN: - case NORTH: - return this.getSize( b.minX, b.maxX, b.minZ, b.maxZ ); - case SOUTH: - case UP: - return this.getSize( b.minX, b.maxX, b.minY, b.maxY ); - default: + case WEST: + case EAST: + return this.getSize( b.minZ, b.maxZ, b.minY, b.maxY ); + case DOWN: + case NORTH: + return this.getSize( b.minX, b.maxX, b.minZ, b.maxZ ); + case SOUTH: + case UP: + return this.getSize( b.minX, b.maxX, b.minY, b.maxY ); + default: } } return 12; } - int getSize(double a, double b, double c, double d) + int getSize( double a, double b, double c, double d ) { double r = Math.abs( a - 0.5 ); r = Math.max( Math.abs( b - 0.5 ), r ); r = Math.max( Math.abs( c - 0.5 ), r ); - return (8 * (int) Math.max( Math.abs( d - 0.5 ), r )); + return ( 8 * (int) Math.max( Math.abs( d - 0.5 ), r ) ); } // @Override @@ -629,15 +430,211 @@ public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IReds { int mask = 0; - for (ForgeDirection side : ForgeDirection.values()) + for( ForgeDirection side : ForgeDirection.values() ) { - if ( this.getPart( side ) != null ) + if( this.getPart( side ) != null ) mask |= 1 << side.ordinal(); - else if ( side != ForgeDirection.UNKNOWN && this.getFacadeContainer().getFacade( side ) != null ) + else if( side != ForgeDirection.UNKNOWN && this.getFacadeContainer().getFacade( side ) != null ) mask |= 1 << side.ordinal(); } return mask; } + @Override + public IFacadeContainer getFacadeContainer() + { + return this.cb.getFacadeContainer(); + } + + @Override + public boolean canAddPart( ItemStack is, ForgeDirection side ) + { + IFacadePart fp = PartPlacement.isFacade( is, side ); + if( fp != null ) + { + if( !( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) ) + { + List boxes = new ArrayList(); + IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); + fp.getBoxes( bch, null ); + for( AxisAlignedBB bb : boxes ) + { + DISABLE_FACADE_OCCLUSION.set( true ); + boolean canAdd = this.tile().canAddPart( new NormallyOccludedPart( new Cuboid6( bb ) ) ); + DISABLE_FACADE_OCCLUSION.remove(); + if( !canAdd ) + { + return false; + } + } + } + return true; + } + + if( is.getItem() instanceof IPartItem ) + { + IPartItem bi = (IPartItem) is.getItem(); + + is = is.copy(); + is.stackSize = 1; + + IPart bp = bi.createPartFromItemStack( is ); + if( !( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) ) + { + List boxes = new ArrayList(); + IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); + bp.getBoxes( bch ); + for( AxisAlignedBB bb : boxes ) + { + if( !this.tile().canAddPart( new NormallyOccludedPart( new Cuboid6( bb ) ) ) ) + { + return false; + } + } + } + } + + return this.cb.canAddPart( is, side ); + } + + @Override + public ForgeDirection addPart( ItemStack is, ForgeDirection side, EntityPlayer owner ) + { + return this.cb.addPart( is, side, owner ); + } + + @Override + public IPart getPart( ForgeDirection side ) + { + return this.cb.getPart( side ); + } + + @Override + public void removePart( ForgeDirection side, boolean suppressUpdate ) + { + this.cb.removePart( side, suppressUpdate ); + } + + @Override + public void markForUpdate() + { + if( Platform.isServer() && this.canUpdate ) + this.sendDescUpdate(); + } + + @Override + public DimensionalCoord getLocation() + { + return new DimensionalCoord( this.tile() ); + } + + @Override + public AEColor getColor() + { + return this.cb.getColor(); + } + + @Override + public void clearContainer() + { + this.cb = new CableBusContainer( this ); + } @Override + public Iterable getCollisionBoxes() + { + LinkedList l = new LinkedList(); + for( AxisAlignedBB b : this.cb.getSelectedBoundingBoxesFromPool( false, true, null, true ) ) + { + l.add( new Cuboid6( b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ ) ); + } + return l; + } + + @Override + public boolean isBlocked( ForgeDirection side ) + { + if( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) + return false; + + DISABLE_FACADE_OCCLUSION.set( true ); + boolean blocked = !this.tile().canAddPart( new NormallyOccludedPart( SIDE_TESTS[side.ordinal()] ) ); + DISABLE_FACADE_OCCLUSION.remove(); + + return blocked; + } + + @Override + public SelectedPart selectPart( Vec3 pos ) + { + return this.cb.selectPart( pos ); + } + + @Override + public void markForSave() + { + // mark the chunk for save... + TileEntity te = this.tile(); + if( te != null && te.getWorldObj() != null ) + te.getWorldObj().getChunkFromBlockCoords( this.x(), this.z() ).isModified = true; + } + + @Override + public void partChanged() + { + if( this.isInWorld() ) + this.notifyNeighbors(); + } + + @Override + public boolean hasRedstone( ForgeDirection side ) + { + return this.cb.hasRedstone( side ); + } + + @Override + public boolean isEmpty() + { + return this.cb.isEmpty(); + } + + @Override + public Set getLayerFlags() + { + return this.cb.getLayerFlags(); + } @Override + public Iterable getSubParts() + { + LinkedList l = new LinkedList(); + for( Cuboid6 c : this.getCollisionBoxes() ) + { + l.add( new IndexedCuboid6( 0, c ) ); + } + return l; + } + + @Override + public void cleanup() + { + this.tile().remPart( this ); + } + + @Override + public void notifyNeighbors() + { + if( this.tile() instanceof TIInventoryTile ) + ( (TIInventoryTile) this.tile() ).rebuildSlotMap(); + + if( this.world() != null && this.world().blockExists( this.x(), this.y(), this.z() ) && !CableBusContainer.isLoading() ) + Platform.notifyBlocksOfNeighbors( this.world(), this.x(), this.y(), this.z() ); + } + + @Override + public boolean isInWorld() + { + return this.cb.isInWorld(); + } + + + + } diff --git a/src/main/java/appeng/fmp/FMPEvent.java b/src/main/java/appeng/fmp/FMPEvent.java index ff3f9190c..c55b41c08 100644 --- a/src/main/java/appeng/fmp/FMPEvent.java +++ b/src/main/java/appeng/fmp/FMPEvent.java @@ -18,6 +18,7 @@ package appeng.fmp; + import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.entity.player.EntityPlayer; @@ -44,6 +45,7 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketMultiPart; import appeng.integration.modules.helpers.FMPPacketEvent; + /** * Basically a total rip of of the FMP version for vanilla, seemed to work well enough... */ @@ -53,29 +55,15 @@ public class FMPEvent private final ThreadLocal placing = new ThreadLocal(); @SubscribeEvent - public void ServerFMPEvent(FMPPacketEvent event) + public void ServerFMPEvent( FMPPacketEvent event ) { FMPEvent.place( event.sender, event.sender.worldObj ); } - @SubscribeEvent - public void playerInteract(PlayerInteractEvent event) - { - if ( event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote ) - { - if ( this.placing.get() != null ) - return; - this.placing.set( event ); - if ( place( event.entityPlayer, event.entityPlayer.worldObj ) ) - event.setCanceled( true ); - this.placing.set( null ); - } - } - - public static boolean place(EntityPlayer player, World world) + public static boolean place( EntityPlayer player, World world ) { MovingObjectPosition hit = RayTracer.reTrace( world, player ); - if ( hit == null ) + if( hit == null ) return false; BlockCoord pos = new BlockCoord( hit.blockX, hit.blockY, hit.blockZ ).offset( hit.sideHit ); @@ -84,47 +72,44 @@ public class FMPEvent Block blk = null; - if ( held == null ) + if( held == null ) return false; - if ( held.getItem() instanceof AEBaseItemBlock ) + if( held.getItem() instanceof AEBaseItemBlock ) { AEBaseItemBlock ib = (AEBaseItemBlock) held.getItem(); blk = Block.getBlockFromItem( ib ); part = PartRegistry.getPartByBlock( blk, hit.sideHit ); } - if ( part == null ) + if( part == null ) return false; - if ( world.isRemote && !player.isSneaking() )// attempt to use block activated like normal and tell the server - // the right stuff + if( world.isRemote && !player.isSneaking() )// attempt to use block activated like normal and tell the server + // the right stuff { Vector3 f = new Vector3( hit.hitVec ).add( -hit.blockX, -hit.blockY, -hit.blockZ ); Block block = world.getBlock( hit.blockX, hit.blockY, hit.blockZ ); - if ( block != null && !ignoreActivate( block ) - && block.onBlockActivated( world, hit.blockX, hit.blockY, hit.blockZ, player, hit.sideHit, (float) f.x, (float) f.y, (float) f.z ) ) + if( block != null && !ignoreActivate( block ) && block.onBlockActivated( world, hit.blockX, hit.blockY, hit.blockZ, player, hit.sideHit, (float) f.x, (float) f.y, (float) f.z ) ) { player.swingItem(); - PacketCustom.sendToServer( new C08PacketPlayerBlockPlacement( hit.blockX, hit.blockY, hit.blockZ, hit.sideHit, player.inventory - .getCurrentItem(), (float) f.x, (float) f.y, (float) f.z ) ); + PacketCustom.sendToServer( new C08PacketPlayerBlockPlacement( hit.blockX, hit.blockY, hit.blockZ, hit.sideHit, player.inventory.getCurrentItem(), (float) f.x, (float) f.y, (float) f.z ) ); return true; } } TileMultipart tile = TileMultipart.getOrConvertTile( world, pos ); - if ( tile == null || !tile.canAddPart( part ) ) + if( tile == null || !tile.canAddPart( part ) ) return false; - if ( !world.isRemote ) + if( !world.isRemote ) { TileMultipart.addPart( world, pos, part ); - world.playSoundEffect( pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, blk.stepSound.func_150496_b(), (blk.stepSound.getVolume() + 1.0F) / 2.0F, - blk.stepSound.getPitch() * 0.8F ); - if ( !player.capabilities.isCreativeMode ) + world.playSoundEffect( pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, blk.stepSound.func_150496_b(), ( blk.stepSound.getVolume() + 1.0F ) / 2.0F, blk.stepSound.getPitch() * 0.8F ); + if( !player.capabilities.isCreativeMode ) { held.stackSize--; - if ( held.stackSize == 0 ) + if( held.stackSize == 0 ) { player.inventory.mainInventory[player.inventory.currentItem] = null; MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); @@ -142,10 +127,24 @@ public class FMPEvent /** * Because vanilla is weird. */ - private static boolean ignoreActivate(Block block) + private static boolean ignoreActivate( Block block ) { - if ( block instanceof BlockFence ) + if( block instanceof BlockFence ) return true; return false; } + + @SubscribeEvent + public void playerInteract( PlayerInteractEvent event ) + { + if( event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote ) + { + if( this.placing.get() != null ) + return; + this.placing.set( event ); + if( place( event.entityPlayer, event.entityPlayer.worldObj ) ) + event.setCanceled( true ); + this.placing.set( null ); + } + } } diff --git a/src/main/java/appeng/fmp/FMPPlacementHelper.java b/src/main/java/appeng/fmp/FMPPlacementHelper.java index cb22046cd..74fadf5de 100644 --- a/src/main/java/appeng/fmp/FMPPlacementHelper.java +++ b/src/main/java/appeng/fmp/FMPPlacementHelper.java @@ -18,6 +18,7 @@ package appeng.fmp; + import java.util.EnumSet; import java.util.Set; @@ -43,89 +44,30 @@ import appeng.facade.FacadeContainer; import appeng.parts.CableBusStorage; import appeng.util.Platform; + public class FMPPlacementHelper implements IPartHost { - static class NullStorage extends CableBusStorage - { - - @Override - public IFacadePart getFacade(int x) - { - return null; - } - - @Override - public void setFacade(int x, IFacadePart facade) - { - - } - - } - final private static CableBusStorage NULL_STORAGE = new NullStorage(); - private boolean hasPart = false; private TileMultipart myMP; private CableBusPart myPart; - private CableBusPart getPart() + public FMPPlacementHelper( TileMultipart mp ) { - scala.collection.Iterator i = this.myMP.partList().iterator(); - while (i.hasNext()) - { - TMultiPart p = i.next(); - if ( p instanceof CableBusPart ) - this.myPart = (CableBusPart) p; - } - - if ( this.myPart == null ) - this.myPart = (CableBusPart) PartRegistry.CableBusPart.construct( 0 ); - - BlockCoord loc = new BlockCoord( this.myMP.xCoord, this.myMP.yCoord, this.myMP.zCoord ); - - if ( this.myMP.canAddPart( this.myPart ) && Platform.isServer() ) - { - this.myMP = TileMultipart.addPart( this.myMP.getWorldObj(), loc, this.myPart ); - this.hasPart = true; - } - - return this.myPart; - } - - public void removePart() - { - if ( this.myPart.isEmpty() ) - { - scala.collection.Iterator i = this.myMP.partList().iterator(); - while (i.hasNext()) - { - TMultiPart p = i.next(); - if ( p == this.myPart ) - { - this.myMP = this.myMP.remPart( this.myPart ); - break; - } - } - this.hasPart = false; - this.myPart = null; - } - } - - public FMPPlacementHelper(TileMultipart mp) { this.myMP = mp; } @Override public IFacadeContainer getFacadeContainer() { - if ( this.myPart == null ) + if( this.myPart == null ) return new FacadeContainer( NULL_STORAGE ); return this.myPart.getFacadeContainer(); } @Override - public boolean canAddPart(ItemStack part, ForgeDirection side) + public boolean canAddPart( ItemStack part, ForgeDirection side ) { CableBusPart myPart = this.getPart(); @@ -136,8 +78,51 @@ public class FMPPlacementHelper implements IPartHost return returnValue; } + private CableBusPart getPart() + { + scala.collection.Iterator i = this.myMP.partList().iterator(); + while( i.hasNext() ) + { + TMultiPart p = i.next(); + if( p instanceof CableBusPart ) + this.myPart = (CableBusPart) p; + } + + if( this.myPart == null ) + this.myPart = (CableBusPart) PartRegistry.CableBusPart.construct( 0 ); + + BlockCoord loc = new BlockCoord( this.myMP.xCoord, this.myMP.yCoord, this.myMP.zCoord ); + + if( this.myMP.canAddPart( this.myPart ) && Platform.isServer() ) + { + this.myMP = TileMultipart.addPart( this.myMP.getWorldObj(), loc, this.myPart ); + this.hasPart = true; + } + + return this.myPart; + } + + public void removePart() + { + if( this.myPart.isEmpty() ) + { + scala.collection.Iterator i = this.myMP.partList().iterator(); + while( i.hasNext() ) + { + TMultiPart p = i.next(); + if( p == this.myPart ) + { + this.myMP = this.myMP.remPart( this.myPart ); + break; + } + } + this.hasPart = false; + this.myPart = null; + } + } + @Override - public ForgeDirection addPart(ItemStack is, ForgeDirection side, EntityPlayer owner) + public ForgeDirection addPart( ItemStack is, ForgeDirection side, EntityPlayer owner ) { CableBusPart myPart = this.getPart(); @@ -149,17 +134,17 @@ public class FMPPlacementHelper implements IPartHost } @Override - public IPart getPart(ForgeDirection side) + public IPart getPart( ForgeDirection side ) { - if ( this.myPart == null ) + if( this.myPart == null ) return null; return this.myPart.getPart( side ); } @Override - public void removePart(ForgeDirection side, boolean suppressUpdate) + public void removePart( ForgeDirection side, boolean suppressUpdate ) { - if ( this.myPart == null ) + if( this.myPart == null ) return; this.myPart.removePart( side, suppressUpdate ); } @@ -167,7 +152,7 @@ public class FMPPlacementHelper implements IPartHost @Override public void markForUpdate() { - if ( this.myPart == null ) + if( this.myPart == null ) return; this.myPart.markForUpdate(); } @@ -175,7 +160,7 @@ public class FMPPlacementHelper implements IPartHost @Override public DimensionalCoord getLocation() { - if ( this.myPart == null ) + if( this.myPart == null ) return new DimensionalCoord( this.myMP ); return this.myPart.getLocation(); } @@ -189,7 +174,7 @@ public class FMPPlacementHelper implements IPartHost @Override public AEColor getColor() { - if ( this.myPart == null ) + if( this.myPart == null ) return AEColor.Transparent; return this.myPart.getColor(); } @@ -197,13 +182,13 @@ public class FMPPlacementHelper implements IPartHost @Override public void clearContainer() { - if ( this.myPart == null ) + if( this.myPart == null ) return; this.myPart.clearContainer(); } @Override - public boolean isBlocked(ForgeDirection side) + public boolean isBlocked( ForgeDirection side ) { this.getPart(); @@ -215,9 +200,9 @@ public class FMPPlacementHelper implements IPartHost } @Override - public SelectedPart selectPart(Vec3 pos) + public SelectedPart selectPart( Vec3 pos ) { - if ( this.myPart == null ) + if( this.myPart == null ) return new SelectedPart(); return this.myPart.selectPart( pos ); } @@ -225,7 +210,7 @@ public class FMPPlacementHelper implements IPartHost @Override public void markForSave() { - if ( this.myPart == null ) + if( this.myPart == null ) return; this.myPart.markForSave(); } @@ -233,15 +218,15 @@ public class FMPPlacementHelper implements IPartHost @Override public void partChanged() { - if ( this.myPart == null ) + if( this.myPart == null ) return; this.myPart.partChanged(); } @Override - public boolean hasRedstone(ForgeDirection side) + public boolean hasRedstone( ForgeDirection side ) { - if ( this.myPart == null ) + if( this.myPart == null ) return false; return this.myPart.hasRedstone( side ); } @@ -249,7 +234,7 @@ public class FMPPlacementHelper implements IPartHost @Override public boolean isEmpty() { - if ( this.myPart == null ) + if( this.myPart == null ) return true; return this.myPart.isEmpty(); } @@ -257,7 +242,7 @@ public class FMPPlacementHelper implements IPartHost @Override public Set getLayerFlags() { - if ( this.myPart == null ) + if( this.myPart == null ) return EnumSet.noneOf( LayerFlags.class ); return this.myPart.getLayerFlags(); } @@ -265,7 +250,7 @@ public class FMPPlacementHelper implements IPartHost @Override public void cleanup() { - if ( this.myPart == null ) + if( this.myPart == null ) return; this.myPart.cleanup(); } @@ -273,7 +258,7 @@ public class FMPPlacementHelper implements IPartHost @Override public void notifyNeighbors() { - if ( this.myPart == null ) + if( this.myPart == null ) return; this.myPart.notifyNeighbors(); } @@ -281,9 +266,24 @@ public class FMPPlacementHelper implements IPartHost @Override public boolean isInWorld() { - if ( this.myPart == null ) + if( this.myPart == null ) return this.myMP.getWorldObj() != null; return this.myPart.isInWorld(); } + static class NullStorage extends CableBusStorage + { + + @Override + public IFacadePart getFacade( int x ) + { + return null; + } + + @Override + public void setFacade( int x, IFacadePart facade ) + { + + } + } } diff --git a/src/main/java/appeng/fmp/PartRegistry.java b/src/main/java/appeng/fmp/PartRegistry.java index c36a40866..eb3d8ba95 100644 --- a/src/main/java/appeng/fmp/PartRegistry.java +++ b/src/main/java/appeng/fmp/PartRegistry.java @@ -18,6 +18,7 @@ package appeng.fmp; + import net.minecraft.block.Block; import codechicken.multipart.TMultiPart; @@ -27,46 +28,28 @@ import appeng.block.misc.BlockQuartzTorch; import appeng.block.networking.BlockCableBus; import appeng.core.Api; + public enum PartRegistry { - QuartzTorchPart("ae2_torch", BlockQuartzTorch.class, QuartzTorchPart.class), CableBusPart("ae2_cablebus", BlockCableBus.class, CableBusPart.class); + QuartzTorchPart( "ae2_torch", BlockQuartzTorch.class, QuartzTorchPart.class ), CableBusPart( "ae2_cablebus", BlockCableBus.class, CableBusPart.class ); final private String name; final private Class blk; final private Class part; - public String getName() + PartRegistry( String name, Class blk, Class part ) { - return this.name; - } - - PartRegistry( String name, Class blk, Class part ) { this.name = name; this.blk = blk; this.part = part; } - public TMultiPart construct(int meta) - { - try - { - if ( this == CableBusPart ) - return (TMultiPart) Api.INSTANCE.getPartHelper().getCombinedInstance( this.part.getName() ).newInstance(); - else - return this.part.getConstructor( int.class ).newInstance( meta ); - } - catch (Throwable t) - { - throw new RuntimeException( t ); - } - } - - public static String getPartName(TMultiPart part) + public static String getPartName( TMultiPart part ) { Class c = part.getClass(); - for (PartRegistry pr : values()) + for( PartRegistry pr : values() ) { - if ( pr.equals( c ) ) + if( pr.equals( c ) ) { return pr.name; } @@ -74,11 +57,11 @@ public enum PartRegistry throw new RuntimeException( "Invalid PartName" ); } - public static TMultiPart getPartByBlock(Block block, int meta) + public static TMultiPart getPartByBlock( Block block, int meta ) { - for (PartRegistry pr : values()) + for( PartRegistry pr : values() ) { - if ( pr.blk.isInstance( block ) ) + if( pr.blk.isInstance( block ) ) { return pr.construct( meta ); } @@ -86,15 +69,35 @@ public enum PartRegistry return null; } - public static boolean isPart(Block block) + public TMultiPart construct( int meta ) { - for (PartRegistry pr : values()) + try { - if ( pr.blk.isInstance( block ) ) + if( this == CableBusPart ) + return (TMultiPart) Api.INSTANCE.getPartHelper().getCombinedInstance( this.part.getName() ).newInstance(); + else + return this.part.getConstructor( int.class ).newInstance( meta ); + } + catch( Throwable t ) + { + throw new RuntimeException( t ); + } + } + + public static boolean isPart( Block block ) + { + for( PartRegistry pr : values() ) + { + if( pr.blk.isInstance( block ) ) { return true; } } return false; } + + public String getName() + { + return this.name; + } } diff --git a/src/main/java/appeng/fmp/QuartzTorchPart.java b/src/main/java/appeng/fmp/QuartzTorchPart.java index 2a13a4546..11dd03f0c 100644 --- a/src/main/java/appeng/fmp/QuartzTorchPart.java +++ b/src/main/java/appeng/fmp/QuartzTorchPart.java @@ -18,6 +18,7 @@ package appeng.fmp; + import java.util.Random; import net.minecraft.block.Block; @@ -37,31 +38,33 @@ import appeng.api.exceptions.MissingDefinition; public class QuartzTorchPart extends McSidedMetaPart implements IRandomDisplayTick { - public QuartzTorchPart() { + public QuartzTorchPart() + { this( ForgeDirection.DOWN.ordinal() ); } - public QuartzTorchPart(int meta) { + public QuartzTorchPart( int meta ) + { super( meta ); } + public static McBlockPart placement( World world, BlockCoord pos, int side ) + { + pos = pos.copy().offset( side ); + if( !world.isSideSolid( pos.x, pos.y, pos.z, ForgeDirection.getOrientation( side ) ) ) + { + return null; + } + + return new QuartzTorchPart( side ); + } + @Override public boolean doesTick() { return false; } - @Override - public Block getBlock() - { - for ( Block torchBlock : AEApi.instance().definitions().blocks().quartzTorch().maybeBlock().asSet() ) - { - return torchBlock; - } - - throw new MissingDefinition( "Tried to retrieve a quartz torch, even though it is disabled." ); - } - @Override public String getType() { @@ -74,7 +77,7 @@ public class QuartzTorchPart extends McSidedMetaPart implements IRandomDisplayTi return this.getBounds( this.meta ); } - public Cuboid6 getBounds(int meta) + public Cuboid6 getBounds( int meta ) { ForgeDirection up = ForgeDirection.getOrientation( meta ); double xOff = -0.3 * up.offsetX; @@ -84,25 +87,25 @@ public class QuartzTorchPart extends McSidedMetaPart implements IRandomDisplayTi } @Override - public int sideForMeta(int meta) + public int sideForMeta( int meta ) { return ForgeDirection.getOrientation( meta ).getOpposite().ordinal(); } - public static McBlockPart placement(World world, BlockCoord pos, int side) - { - pos = pos.copy().offset( side ); - if ( !world.isSideSolid( pos.x, pos.y, pos.z, ForgeDirection.getOrientation( side ) ) ) - { - return null; - } - - return new QuartzTorchPart( side ); - } - @Override - public void randomDisplayTick(Random r) + public void randomDisplayTick( Random r ) { this.getBlock().randomDisplayTick( this.world(), this.x(), this.y(), this.z(), r ); } + + @Override + public Block getBlock() + { + for( Block torchBlock : AEApi.instance().definitions().blocks().quartzTorch().maybeBlock().asSet() ) + { + return torchBlock; + } + + throw new MissingDefinition( "Tried to retrieve a quartz torch, even though it is disabled." ); + } } \ No newline at end of file diff --git a/src/main/java/appeng/helpers/AEGlassMaterial.java b/src/main/java/appeng/helpers/AEGlassMaterial.java index 43589f537..c14028832 100644 --- a/src/main/java/appeng/helpers/AEGlassMaterial.java +++ b/src/main/java/appeng/helpers/AEGlassMaterial.java @@ -18,13 +18,18 @@ package appeng.helpers; + import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; + public class AEGlassMaterial extends Material { - public AEGlassMaterial(MapColor p_i2116_1_) { + public static final AEGlassMaterial INSTANCE = ( new AEGlassMaterial( MapColor.airColor ) ); + + public AEGlassMaterial( MapColor p_i2116_1_ ) + { super( p_i2116_1_ ); } @@ -33,7 +38,4 @@ public class AEGlassMaterial extends Material { return false; } - - public static final AEGlassMaterial INSTANCE = (new AEGlassMaterial( MapColor.airColor )); - } diff --git a/src/main/java/appeng/helpers/AEMultiTile.java b/src/main/java/appeng/helpers/AEMultiTile.java index 22097155a..de8165324 100644 --- a/src/main/java/appeng/helpers/AEMultiTile.java +++ b/src/main/java/appeng/helpers/AEMultiTile.java @@ -18,10 +18,12 @@ package appeng.helpers; + import appeng.api.implementations.tiles.IColorableTile; import appeng.api.networking.IGridHost; import appeng.api.parts.IPartHost; + public interface AEMultiTile extends IGridHost, IPartHost, IColorableTile { diff --git a/src/main/java/appeng/helpers/DualityInterface.java b/src/main/java/appeng/helpers/DualityInterface.java index 094b3984b..8d56b8f92 100644 --- a/src/main/java/appeng/helpers/DualityInterface.java +++ b/src/main/java/appeng/helpers/DualityInterface.java @@ -95,127 +95,35 @@ import appeng.util.inv.IInventoryDestination; import appeng.util.inv.WrapperInvSlot; import appeng.util.item.AEItemStack; -public class DualityInterface implements IGridTickable, IStorageMonitorable, IInventoryDestination, IAEAppEngInventory, - IConfigManagerHost, ICraftingProvider, IUpgradeableHost, IPriorityHost + +public class DualityInterface implements IGridTickable, IStorageMonitorable, IInventoryDestination, IAEAppEngInventory, IConfigManagerHost, ICraftingProvider, IUpgradeableHost, IPriorityHost { + static final Set badBlocks = new HashSet(); + static private boolean interfaceRequest = false; final int[] sides = new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }; final IAEItemStack[] requireWork = new IAEItemStack[] { null, null, null, null, null, null, null, null }; final MultiCraftingTracker craftingTracker; - - boolean hasConfig = false; final AENetworkProxy gridProxy; final IInterfaceHost iHost; final BaseActionSource mySrc; final ConfigManager cm = new ConfigManager( this ); + final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 8 ); + final AppEngInternalInventory storage = new AppEngInternalInventory( this, 8 ); + final AppEngInternalInventory patterns = new AppEngInternalInventory( this, 9 ); + final WrapperInvSlot slotInv = new WrapperInvSlot( this.storage ); + final MEMonitorPassThrough items = new MEMonitorPassThrough( new NullInventory(), StorageChannel.ITEMS ); + final MEMonitorPassThrough fluids = new MEMonitorPassThrough( new NullInventory(), StorageChannel.FLUIDS ); + private final UpgradeInventory upgrades; + boolean hasConfig = false; int priority; - List craftingList = null; List waitingToSend = null; + IMEInventory destination; + private boolean isWorking = false; - private final UpgradeInventory upgrades; - - @Override - public int getInstalledUpgrades(Upgrades u) + public DualityInterface( AENetworkProxy networkProxy, IInterfaceHost ih ) { - if ( this.upgrades == null ) - return 0; - return this.upgrades.getInstalledUpgrades( u ); - } - - public boolean hasItemsToSend() - { - return this.waitingToSend != null && !this.waitingToSend.isEmpty(); - } - - public void updateCraftingList() - { - Boolean[] accountedFor = new Boolean[] { false, false, false, false, false, false, false, false, false }; // 9... - - assert (accountedFor.length == this.patterns.getSizeInventory()); - - if ( !this.gridProxy.isReady() ) - return; - - if ( this.craftingList != null ) - { - Iterator i = this.craftingList.iterator(); - while (i.hasNext()) - { - ICraftingPatternDetails details = i.next(); - boolean found = false; - - for (int x = 0; x < accountedFor.length; x++) - { - ItemStack is = this.patterns.getStackInSlot( x ); - if ( details.getPattern() == is ) - { - accountedFor[x] = found = true; - } - } - - if ( !found ) - i.remove(); - } - } - - for (int x = 0; x < accountedFor.length; x++) - { - if ( !accountedFor[x] ) - this.addToCraftingList( this.patterns.getStackInSlot( x ) ); - } - - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - } - catch (GridAccessException e) - { - // :P - } - } - - public void addToCraftingList(ItemStack is) - { - if ( is == null ) - return; - - if ( is.getItem() instanceof ICraftingPatternItem ) - { - ICraftingPatternItem cpi = (ICraftingPatternItem) is.getItem(); - ICraftingPatternDetails details = cpi.getPatternForItem( is, this.iHost.getTileEntity().getWorldObj() ); - - if ( details != null ) - { - if ( this.craftingList == null ) - this.craftingList = new LinkedList(); - - this.craftingList.add( details ); - } - } - } - - public void addToSendList(ItemStack is) - { - if ( is == null ) - return; - - if ( this.waitingToSend == null ) - this.waitingToSend = new LinkedList(); - - this.waitingToSend.add( is ); - - try - { - this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); - } - catch (GridAccessException e) - { - // :P - } - } - - public DualityInterface(AENetworkProxy networkProxy, IInterfaceHost ih) { this.gridProxy = networkProxy; this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); @@ -234,45 +142,42 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn this.iHost.saveChanges(); } - private void readConfig() + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) { - this.hasConfig = false; + if( this.isWorking ) + return; - for (ItemStack p : this.config) + if( inv == this.config ) + this.readConfig(); + else if( inv == this.patterns && ( removed != null || added != null ) ) + this.updateCraftingList(); + else if( inv == this.storage && slot >= 0 ) { - if ( p != null ) + boolean had = this.hasWorkToDo(); + + this.updatePlan( slot ); + + boolean now = this.hasWorkToDo(); + + if( had != now ) { - this.hasConfig = true; - break; + try + { + if( now ) + this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); + else + this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); + } + catch( GridAccessException e ) + { + // :P + } } } - - boolean had = this.hasWorkToDo(); - - for (int x = 0; x < 8; x++) - this.updatePlan( x ); - - boolean has = this.hasWorkToDo(); - - if ( had != has ) - { - try - { - if ( has ) - this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); - else - this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); - } - catch (GridAccessException e) - { - // :P - } - } - - this.notifyNeighbors(); } - public void writeToNBT(NBTTagCompound data) + public void writeToNBT( NBTTagCompound data ) { this.config.writeToNBT( data, "config" ); this.patterns.writeToNBT( data, "patterns" ); @@ -283,9 +188,9 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn data.setInteger( "priority", this.priority ); NBTTagList waitingToSend = new NBTTagList(); - if ( this.waitingToSend != null ) + if( this.waitingToSend != null ) { - for (ItemStack is : this.waitingToSend) + for( ItemStack is : this.waitingToSend ) { NBTTagCompound item = new NBTTagCompound(); is.writeToNBT( item ); @@ -295,16 +200,16 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn data.setTag( "waitingToSend", waitingToSend ); } - public void readFromNBT(NBTTagCompound data) + public void readFromNBT( NBTTagCompound data ) { this.waitingToSend = null; NBTTagList waitingList = data.getTagList( "waitingToSend", 10 ); - if ( waitingList != null ) + if( waitingList != null ) { - for (int x = 0; x < waitingList.tagCount(); x++) + for( int x = 0; x < waitingList.tagCount(); x++ ) { NBTTagCompound c = waitingList.getCompoundTagAt( x ); - if ( c != null ) + if( c != null ) { ItemStack is = ItemStack.loadItemStackFromNBT( c ); this.addToSendList( is ); @@ -323,37 +228,120 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn this.updateCraftingList(); } - final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 8 ); - final AppEngInternalInventory storage = new AppEngInternalInventory( this, 8 ); - final AppEngInternalInventory patterns = new AppEngInternalInventory( this, 9 ); - - final WrapperInvSlot slotInv = new WrapperInvSlot( this.storage ); - - private InventoryAdaptor getAdaptor(int slot) + public void addToSendList( ItemStack is ) { - return new AdaptorIInventory( this.slotInv.getWrapper( slot ) ); + if( is == null ) + return; + + if( this.waitingToSend == null ) + this.waitingToSend = new LinkedList(); + + this.waitingToSend.add( is ); + + try + { + this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); + } + catch( GridAccessException e ) + { + // :P + } } - IMEInventory destination; - private boolean isWorking = false; - - @Override - public boolean canInsert(ItemStack stack) + private void readConfig() { - IAEItemStack out = this.destination.injectItems( AEApi.instance().storage().createItemStack( stack ), Actionable.SIMULATE, null ); - if ( out == null ) - return true; - return out.getStackSize() != stack.stackSize; - // ItemStack after = adaptor.simulateAdd( stack ); - // if ( after == null ) - // return true; - // return after.stackSize != stack.stackSize; + this.hasConfig = false; + + for( ItemStack p : this.config ) + { + if( p != null ) + { + this.hasConfig = true; + break; + } + } + + boolean had = this.hasWorkToDo(); + + for( int x = 0; x < 8; x++ ) + this.updatePlan( x ); + + boolean has = this.hasWorkToDo(); + + if( had != has ) + { + try + { + if( has ) + this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); + else + this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); + } + catch( GridAccessException e ) + { + // :P + } + } + + this.notifyNeighbors(); } - private void updatePlan(int slot) + public void updateCraftingList() + { + Boolean[] accountedFor = new Boolean[] { false, false, false, false, false, false, false, false, false }; // 9... + + assert ( accountedFor.length == this.patterns.getSizeInventory() ); + + if( !this.gridProxy.isReady() ) + return; + + if( this.craftingList != null ) + { + Iterator i = this.craftingList.iterator(); + while( i.hasNext() ) + { + ICraftingPatternDetails details = i.next(); + boolean found = false; + + for( int x = 0; x < accountedFor.length; x++ ) + { + ItemStack is = this.patterns.getStackInSlot( x ); + if( details.getPattern() == is ) + { + accountedFor[x] = found = true; + } + } + + if( !found ) + i.remove(); + } + } + + for( int x = 0; x < accountedFor.length; x++ ) + { + if( !accountedFor[x] ) + this.addToCraftingList( this.patterns.getStackInSlot( x ) ); + } + + try + { + this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); + } + catch( GridAccessException e ) + { + // :P + } + } + + public boolean hasWorkToDo() + { + return this.hasItemsToSend() || this.requireWork[0] != null || this.requireWork[1] != null || this.requireWork[2] != null || this.requireWork[3] != null || this.requireWork[4] != null || this.requireWork[5] != null || this.requireWork[6] != null || this.requireWork[7] != null; + } + + private void updatePlan( int slot ) { IAEItemStack req = this.config.getAEStackInSlot( slot ); - if ( req != null && req.getStackSize() <= 0 ) + if( req != null && req.getStackSize() <= 0 ) { this.config.setInventorySlotContents( slot, null ); req = null; @@ -361,22 +349,22 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn ItemStack Stored = this.storage.getStackInSlot( slot ); - if ( req == null && Stored != null ) + if( req == null && Stored != null ) { IAEItemStack work = AEApi.instance().storage().createItemStack( Stored ); this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); return; } - else if ( req != null ) + else if( req != null ) { - if ( Stored == null ) // need to add stuff! + if( Stored == null ) // need to add stuff! { this.requireWork[slot] = req.copy(); return; } - else if ( req.isSameType( Stored ) ) // same type ( qty different? )! + else if( req.isSameType( Stored ) ) // same type ( qty different? )! { - if ( req.getStackSize() != Stored.stackSize ) + if( req.getStackSize() != Stored.stackSize ) { this.requireWork[slot] = req.copy(); this.requireWork[slot].setStackSize( req.getStackSize() - Stored.stackSize ); @@ -396,130 +384,62 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn this.requireWork[slot] = null; } - static private boolean interfaceRequest = false; - - class InterfaceInventory extends MEMonitorIInventory + public void notifyNeighbors() { - - public InterfaceInventory(DualityInterface tileInterface) { - super( new AdaptorIInventory( tileInterface.storage ) ); - this.mySource = new MachineSource( DualityInterface.this.iHost ); - } - - @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable type, BaseActionSource src) + if( this.gridProxy.isActive() ) { - if ( interfaceRequest ) - return input; - - return super.injectItems( input, type, src ); - } - - @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable type, BaseActionSource src) - { - if ( interfaceRequest ) - return null; - - return super.extractItems( request, type, src ); + try + { + this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); + this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); + } + catch( GridAccessException e ) + { + // :P + } } + TileEntity te = this.iHost.getTileEntity(); + if( te != null && te.getWorldObj() != null ) + Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); } - private boolean usePlan(int x, IAEItemStack itemStack) + public void addToCraftingList( ItemStack is ) { - boolean changed = false; - InventoryAdaptor adaptor = this.getAdaptor( x ); - interfaceRequest = this.isWorking = true; + if( is == null ) + return; - try + if( is.getItem() instanceof ICraftingPatternItem ) { - this.destination = this.gridProxy.getStorage().getItemInventory(); - IEnergySource src = this.gridProxy.getEnergy(); + ICraftingPatternItem cpi = (ICraftingPatternItem) is.getItem(); + ICraftingPatternDetails details = cpi.getPatternForItem( is, this.iHost.getTileEntity().getWorldObj() ); - if ( this.craftingTracker.isBusy( x ) ) - changed = this.handleCrafting( x, adaptor, itemStack ) || changed; - else if ( itemStack.getStackSize() > 0 ) + if( details != null ) { - // make sure strange things didn't happen... - if ( adaptor.simulateAdd( itemStack.getItemStack() ) != null ) - { - changed = true; - throw new GridAccessException(); - } + if( this.craftingList == null ) + this.craftingList = new LinkedList(); - IAEItemStack acquired = Platform.poweredExtraction( src, this.destination, itemStack, this.mySrc ); - if ( acquired != null ) - { - changed = true; - ItemStack issue = adaptor.addItems( acquired.getItemStack() ); - if ( issue != null ) - throw new RuntimeException( "bad attempt at managing inventory. ( addItems )" ); - } - else - changed = this.handleCrafting( x, adaptor, itemStack ) || changed; + this.craftingList.add( details ); } - else if ( itemStack.getStackSize() < 0 ) - { - IAEItemStack toStore = itemStack.copy(); - toStore.setStackSize( -toStore.getStackSize() ); - - long diff = toStore.getStackSize(); - - // make sure strange things didn't happen... - ItemStack canExtract = adaptor.simulateRemove( (int) diff, toStore.getItemStack(), null ); - if ( canExtract == null || canExtract.stackSize != diff ) - { - changed = true; - throw new GridAccessException(); - } - - toStore = Platform.poweredInsert( src, this.destination, toStore, this.mySrc ); - - if ( toStore != null ) - diff -= toStore.getStackSize(); - - if ( diff != 0 ) - { - // extract items! - changed = true; - ItemStack removed = adaptor.removeItems( (int) diff, null, null ); - if ( removed == null ) - throw new RuntimeException( "bad attempt at managing inventory. ( removeItems )" ); - else if ( removed.stackSize != diff ) - throw new RuntimeException( "bad attempt at managing inventory. ( removeItems )" ); - } - } - // else wtf? } - catch (GridAccessException e) - { - // :P - } - - if ( changed ) - this.updatePlan( x ); - - interfaceRequest = this.isWorking = false; - return changed; } - private boolean handleCrafting(int x, InventoryAdaptor d, IAEItemStack itemStack) + public boolean hasItemsToSend() { - try - { - if ( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 && itemStack != null ) - { - return this.craftingTracker.handleCrafting( x, itemStack.getStackSize(), itemStack, d, this.iHost.getTileEntity().getWorldObj(), this.gridProxy.getGrid(), - this.gridProxy.getCrafting(), this.mySrc ); - } - } - catch (GridAccessException e) - { - // :P - } + return this.waitingToSend != null && !this.waitingToSend.isEmpty(); + } - return false; + @Override + public boolean canInsert( ItemStack stack ) + { + IAEItemStack out = this.destination.injectItems( AEApi.instance().storage().createItemStack( stack ), Actionable.SIMULATE, null ); + if( out == null ) + return true; + return out.getStackSize() != stack.stackSize; + // ItemStack after = adaptor.simulateAdd( stack ); + // if ( after == null ) + // return true; + // return after.stackSize != stack.stackSize; } public IInventory getConfig() @@ -532,9 +452,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn return this.patterns; } - final MEMonitorPassThrough items = new MEMonitorPassThrough( new NullInventory(), StorageChannel.ITEMS ); - final MEMonitorPassThrough fluids = new MEMonitorPassThrough( new NullInventory(), StorageChannel.FLUIDS ); - public void gridChanged() { try @@ -542,7 +459,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn this.items.setInternal( this.gridProxy.getStorage().getItemInventory() ); this.fluids.setInternal( this.gridProxy.getStorage().getFluidInventory() ); } - catch (GridAccessException gae) + catch( GridAccessException gae ) { this.items.setInternal( new NullInventory() ); this.fluids.setInternal( new NullInventory() ); @@ -551,7 +468,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn this.notifyNeighbors(); } - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.SMART; } @@ -568,58 +485,83 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn public void markDirty() { - for (int slot = 0; slot < this.storage.getSizeInventory(); slot++) + for( int slot = 0; slot < this.storage.getSizeInventory(); slot++ ) this.onChangeInventory( this.storage, slot, InvOperation.markDirty, null, null ); } - @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) + public int[] getAccessibleSlotsFromSide( int side ) { - if ( this.isWorking ) - return; - - if ( inv == this.config ) - this.readConfig(); - else if ( inv == this.patterns && (removed != null || added != null) ) - this.updateCraftingList(); - else if ( inv == this.storage && slot >= 0 ) - { - boolean had = this.hasWorkToDo(); - - this.updatePlan( slot ); - - boolean now = this.hasWorkToDo(); - - if ( had != now ) - { - try - { - if ( now ) - this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); - else - this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); - } - catch (GridAccessException e) - { - // :P - } - } - } + return this.sides; } - public boolean hasWorkToDo() + @Override + public TickingRequest getTickingRequest( IGridNode node ) { - return this.hasItemsToSend() || this.requireWork[0] != null || this.requireWork[1] != null || this.requireWork[2] != null || this.requireWork[3] != null - || this.requireWork[4] != null || this.requireWork[5] != null || this.requireWork[6] != null || this.requireWork[7] != null; + return new TickingRequest( TickRates.Interface.min, TickRates.Interface.max, !this.hasWorkToDo(), true ); + } + + @Override + public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) + { + if( !this.gridProxy.isActive() ) + return TickRateModulation.SLEEP; + + if( this.hasItemsToSend() ) + this.pushItemsOut( EnumSet.allOf( ForgeDirection.class ) ); + + boolean couldDoWork = this.updateStorage(); + return this.hasWorkToDo() ? ( couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER ) : TickRateModulation.SLEEP; + } + + private void pushItemsOut( EnumSet possibleDirections ) + { + if( !this.hasItemsToSend() ) + return; + + TileEntity tile = this.iHost.getTileEntity(); + World w = tile.getWorldObj(); + + Iterator i = this.waitingToSend.iterator(); + while( i.hasNext() ) + { + ItemStack whatToSend = i.next(); + + for( ForgeDirection s : possibleDirections ) + { + TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); + if( te == null ) + continue; + + InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); + if( ad != null ) + { + ItemStack Result = ad.addItems( whatToSend ); + + if( Result == null ) + whatToSend = null; + else + whatToSend.stackSize -= whatToSend.stackSize - Result.stackSize; + + if( whatToSend == null ) + break; + } + } + + if( whatToSend == null ) + i.remove(); + } + + if( this.waitingToSend.isEmpty() ) + this.waitingToSend = null; } private boolean updateStorage() { boolean didSomething = false; - for (int x = 0; x < 8; x++) + for( int x = 0; x < 8; x++ ) { - if ( this.requireWork[x] != null ) + if( this.requireWork[x] != null ) { didSomething = this.usePlan( x, this.requireWork[x] ) || didSomething; } @@ -628,66 +570,147 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn return didSomething; } - public boolean hasConfig() + private boolean usePlan( int x, IAEItemStack itemStack ) { - return this.hasConfig; + boolean changed = false; + InventoryAdaptor adaptor = this.getAdaptor( x ); + interfaceRequest = this.isWorking = true; + + try + { + this.destination = this.gridProxy.getStorage().getItemInventory(); + IEnergySource src = this.gridProxy.getEnergy(); + + if( this.craftingTracker.isBusy( x ) ) + changed = this.handleCrafting( x, adaptor, itemStack ) || changed; + else if( itemStack.getStackSize() > 0 ) + { + // make sure strange things didn't happen... + if( adaptor.simulateAdd( itemStack.getItemStack() ) != null ) + { + changed = true; + throw new GridAccessException(); + } + + IAEItemStack acquired = Platform.poweredExtraction( src, this.destination, itemStack, this.mySrc ); + if( acquired != null ) + { + changed = true; + ItemStack issue = adaptor.addItems( acquired.getItemStack() ); + if( issue != null ) + throw new RuntimeException( "bad attempt at managing inventory. ( addItems )" ); + } + else + changed = this.handleCrafting( x, adaptor, itemStack ) || changed; + } + else if( itemStack.getStackSize() < 0 ) + { + IAEItemStack toStore = itemStack.copy(); + toStore.setStackSize( -toStore.getStackSize() ); + + long diff = toStore.getStackSize(); + + // make sure strange things didn't happen... + ItemStack canExtract = adaptor.simulateRemove( (int) diff, toStore.getItemStack(), null ); + if( canExtract == null || canExtract.stackSize != diff ) + { + changed = true; + throw new GridAccessException(); + } + + toStore = Platform.poweredInsert( src, this.destination, toStore, this.mySrc ); + + if( toStore != null ) + diff -= toStore.getStackSize(); + + if( diff != 0 ) + { + // extract items! + changed = true; + ItemStack removed = adaptor.removeItems( (int) diff, null, null ); + if( removed == null ) + throw new RuntimeException( "bad attempt at managing inventory. ( removeItems )" ); + else if( removed.stackSize != diff ) + throw new RuntimeException( "bad attempt at managing inventory. ( removeItems )" ); + } + } + // else wtf? + } + catch( GridAccessException e ) + { + // :P + } + + if( changed ) + this.updatePlan( x ); + + interfaceRequest = this.isWorking = false; + return changed; } - public int[] getAccessibleSlotsFromSide(int side) + private InventoryAdaptor getAdaptor( int slot ) { - return this.sides; + return new AdaptorIInventory( this.slotInv.getWrapper( slot ) ); + } + + private boolean handleCrafting( int x, InventoryAdaptor d, IAEItemStack itemStack ) + { + try + { + if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 && itemStack != null ) + { + return this.craftingTracker.handleCrafting( x, itemStack.getStackSize(), itemStack, d, this.iHost.getTileEntity().getWorldObj(), this.gridProxy.getGrid(), this.gridProxy.getCrafting(), this.mySrc ); + } + } + catch( GridAccessException e ) + { + // :P + } + + return false; } @Override - public TickingRequest getTickingRequest(IGridNode node) + public int getInstalledUpgrades( Upgrades u ) { - return new TickingRequest( TickRates.Interface.min, TickRates.Interface.max, !this.hasWorkToDo(), true ); + if( this.upgrades == null ) + return 0; + return this.upgrades.getInstalledUpgrades( u ); } @Override - public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) + public TileEntity getTile() { - if ( !this.gridProxy.isActive() ) - return TickRateModulation.SLEEP; - - if ( this.hasItemsToSend() ) - this.pushItemsOut( EnumSet.allOf( ForgeDirection.class ) ); - - boolean couldDoWork = this.updateStorage(); - return this.hasWorkToDo() ? (couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER) : TickRateModulation.SLEEP; + return (TileEntity) ( this.iHost instanceof TileEntity ? this.iHost : null ); } @Override public IMEMonitor getItemInventory() { - if ( this.hasConfig() ) + if( this.hasConfig() ) return new InterfaceInventory( this ); return this.items; } - @Override - public IMEMonitor getFluidInventory() + public boolean hasConfig() { - if ( this.hasConfig() ) - return null; - - return this.fluids; + return this.hasConfig; } @Override - public IInventory getInventoryByName(String name) + public IInventory getInventoryByName( String name ) { - if ( name.equals( "storage" ) ) + if( name.equals( "storage" ) ) return this.storage; - if ( name.equals( "patterns" ) ) + if( name.equals( "patterns" ) ) return this.patterns; - if ( name.equals( "config" ) ) + if( name.equals( "config" ) ) return this.config; - if ( name.equals( "upgrades" ) ) + if( name.equals( "upgrades" ) ) return this.upgrades; return null; @@ -698,17 +721,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn return this.storage; } - @Override - public TileEntity getTile() - { - return (TileEntity) (this.iHost instanceof TileEntity ? this.iHost : null); - } - - public IPart getPart() - { - return (IPart) (this.iHost instanceof IPart ? this.iHost : null); - } - @Override public appeng.api.util.IConfigManager getConfigManager() { @@ -716,12 +728,19 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn } @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { - if ( this.getInstalledUpgrades( Upgrades.CRAFTING ) == 0 ) + if( this.getInstalledUpgrades( Upgrades.CRAFTING ) == 0 ) this.cancelCrafting(); this.markDirty(); + } @Override + public IMEMonitor getFluidInventory() + { + if( this.hasConfig() ) + return null; + + return this.fluids; } private void cancelCrafting() @@ -729,14 +748,15 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn this.craftingTracker.cancel(); } - public IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src, IStorageMonitorable myInterface) + public IStorageMonitorable getMonitorable( ForgeDirection side, BaseActionSource src, IStorageMonitorable myInterface ) { - if ( Platform.canAccess( this.gridProxy, src ) ) + if( Platform.canAccess( this.gridProxy, src ) ) return myInterface; final DualityInterface di = this; - return new IStorageMonitorable() { + return new IStorageMonitorable() + { @Override public IMEMonitor getItemInventory() @@ -753,99 +773,57 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn } @Override - public boolean isBusy() + public boolean pushPattern( ICraftingPatternDetails patternDetails, InventoryCrafting table ) { - if ( this.hasItemsToSend() ) - return true; - - boolean busy = false; - - if ( this.isBlocking() ) - { - EnumSet possibleDirections = this.iHost.getTargets(); - TileEntity tile = this.iHost.getTileEntity(); - World w = tile.getWorldObj(); - - boolean allAreBusy = true; - - for (ForgeDirection s : possibleDirections) - { - TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - - InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if ( ad != null ) - { - if ( ad.simulateRemove( 1, null, null ) == null ) - { - allAreBusy = false; - break; - } - } - } - - busy = allAreBusy; - } - - return busy; - } - - private boolean isBlocking() - { - return this.cm.getSetting( Settings.BLOCK ) == YesNo.YES; - } - - @Override - public boolean pushPattern(ICraftingPatternDetails patternDetails, InventoryCrafting table) - { - if ( this.hasItemsToSend() || !this.gridProxy.isActive() ) + if( this.hasItemsToSend() || !this.gridProxy.isActive() ) return false; TileEntity tile = this.iHost.getTileEntity(); World w = tile.getWorldObj(); EnumSet possibleDirections = this.iHost.getTargets(); - for (ForgeDirection s : possibleDirections) + for( ForgeDirection s : possibleDirections ) { TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - if ( te instanceof IInterfaceHost ) + if( te instanceof IInterfaceHost ) { try { - if ( ((IInterfaceHost) te).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) + if( ( (IInterfaceHost) te ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) continue; } - catch (GridAccessException e) + catch( GridAccessException e ) { continue; } } - if ( te instanceof ICraftingMachine ) + if( te instanceof ICraftingMachine ) { ICraftingMachine cm = (ICraftingMachine) te; - if ( cm.acceptsPlans() ) + if( cm.acceptsPlans() ) { - if ( cm.pushPattern( patternDetails, table, s.getOpposite() ) ) + if( cm.pushPattern( patternDetails, table, s.getOpposite() ) ) return true; continue; } } InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if ( ad != null ) + if( ad != null ) { - if ( this.isBlocking() ) + if( this.isBlocking() ) { - if ( ad.simulateRemove( 1, null, null ) != null ) + if( ad.simulateRemove( 1, null, null ) != null ) continue; } - if ( this.acceptsItems( ad, table ) ) + if( this.acceptsItems( ad, table ) ) { - for (int x = 0; x < table.getSizeInventory(); x++) + for( int x = 0; x < table.getSizeInventory(); x++ ) { ItemStack is = table.getStackInSlot( x ); - if ( is != null ) + if( is != null ) { this.addToSendList( ad.addItems( is ) ); } @@ -859,74 +837,74 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn return false; } - private boolean sameGrid(IGrid grid) throws GridAccessException + @Override + public boolean isBusy() + { + if( this.hasItemsToSend() ) + return true; + + boolean busy = false; + + if( this.isBlocking() ) + { + EnumSet possibleDirections = this.iHost.getTargets(); + TileEntity tile = this.iHost.getTileEntity(); + World w = tile.getWorldObj(); + + boolean allAreBusy = true; + + for( ForgeDirection s : possibleDirections ) + { + TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); + + InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); + if( ad != null ) + { + if( ad.simulateRemove( 1, null, null ) == null ) + { + allAreBusy = false; + break; + } + } + } + + busy = allAreBusy; + } + + return busy; + } + + private boolean sameGrid( IGrid grid ) throws GridAccessException { return grid == this.gridProxy.getGrid(); } - private boolean acceptsItems(InventoryAdaptor ad, InventoryCrafting table) + private boolean isBlocking() { - for (int x = 0; x < table.getSizeInventory(); x++) + return this.cm.getSetting( Settings.BLOCK ) == YesNo.YES; + } + + private boolean acceptsItems( InventoryAdaptor ad, InventoryCrafting table ) + { + for( int x = 0; x < table.getSizeInventory(); x++ ) { ItemStack is = table.getStackInSlot( x ); - if ( is == null ) + if( is == null ) continue; - if ( ad.simulateAdd( is.copy() ) != null ) + if( ad.simulateAdd( is.copy() ) != null ) return false; } return true; } - private void pushItemsOut(EnumSet possibleDirections) - { - if ( !this.hasItemsToSend() ) - return; - - TileEntity tile = this.iHost.getTileEntity(); - World w = tile.getWorldObj(); - - Iterator i = this.waitingToSend.iterator(); - while (i.hasNext()) - { - ItemStack whatToSend = i.next(); - - for (ForgeDirection s : possibleDirections) - { - TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - if ( te == null ) - continue; - - InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if ( ad != null ) - { - ItemStack Result = ad.addItems( whatToSend ); - - if ( Result == null ) - whatToSend = null; - else - whatToSend.stackSize -= whatToSend.stackSize - Result.stackSize; - - if ( whatToSend == null ) - break; - } - } - - if ( whatToSend == null ) - i.remove(); - } - - if ( this.waitingToSend.isEmpty() ) - this.waitingToSend = null; - } - @Override - public void provideCrafting(ICraftingProviderHelper craftingTracker) + public void provideCrafting( ICraftingProviderHelper craftingTracker ) { - if ( this.gridProxy.isActive() && this.craftingList != null ) + if( this.gridProxy.isActive() && this.craftingList != null ) { - for (ICraftingPatternDetails details : this.craftingList) + for( ICraftingPatternDetails details : this.craftingList ) { details.setPriority( this.priority ); craftingTracker.addCraftingOption( this, details ); @@ -934,71 +912,56 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn } } - public void addDrops(List drops) + public void addDrops( List drops ) { - if ( this.waitingToSend != null ) + if( this.waitingToSend != null ) { - for (ItemStack is : this.waitingToSend) - if ( is != null ) + for( ItemStack is : this.waitingToSend ) + if( is != null ) drops.add( is ); } - for (ItemStack is : this.upgrades) - if ( is != null ) + for( ItemStack is : this.upgrades ) + if( is != null ) drops.add( is ); - for (ItemStack is : this.storage) - if ( is != null ) + for( ItemStack is : this.storage ) + if( is != null ) drops.add( is ); - for (ItemStack is : this.patterns) - if ( is != null ) + for( ItemStack is : this.patterns ) + if( is != null ) drops.add( is ); } - public void notifyNeighbors() - { - if ( this.gridProxy.isActive() ) - { - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); - } - catch (GridAccessException e) - { - // :P - } - } - - TileEntity te = this.iHost.getTileEntity(); - if ( te != null && te.getWorldObj() != null ) - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); - } - public IUpgradeableHost getHost() { - if ( this.getPart() instanceof IUpgradeableHost ) + if( this.getPart() instanceof IUpgradeableHost ) return (IUpgradeableHost) this.getPart(); - if ( this.getTile() instanceof IUpgradeableHost ) + if( this.getTile() instanceof IUpgradeableHost ) return (IUpgradeableHost) this.getTile(); return null; } + public IPart getPart() + { + return (IPart) ( this.iHost instanceof IPart ? this.iHost : null ); + } + public ImmutableSet getRequestedJobs() { return this.craftingTracker.getRequestedJobs(); } - public IAEItemStack injectCraftedItems(ICraftingLink link, IAEItemStack acquired, Actionable mode) + public IAEItemStack injectCraftedItems( ICraftingLink link, IAEItemStack acquired, Actionable mode ) { int slot = this.craftingTracker.getSlot( link ); - if ( acquired != null && slot >= 0 && slot <= this.requireWork.length ) + if( acquired != null && slot >= 0 && slot <= this.requireWork.length ) { InventoryAdaptor adaptor = this.getAdaptor( slot ); - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) return AEItemStack.create( adaptor.simulateAdd( acquired.getItemStack() ) ); else { @@ -1011,23 +974,21 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn return acquired; } - public void jobStateChange(ICraftingLink link) + public void jobStateChange( ICraftingLink link ) { this.craftingTracker.jobStateChange( link ); } - static final Set badBlocks = new HashSet(); - public String getTermName() { TileEntity tile = this.iHost.getTileEntity(); World w = tile.getWorldObj(); - if ( ((ICustomNameObject) this.iHost).hasCustomName() ) - return ((ICustomNameObject) this.iHost).getCustomName(); + if( ( (ICustomNameObject) this.iHost ).hasCustomName() ) + return ( (ICustomNameObject) this.iHost ).getCustomName(); EnumSet possibleDirections = this.iHost.getTargets(); - for (ForgeDirection s : possibleDirections) + for( ForgeDirection s : possibleDirections ) { Vec3 from = Vec3.createVectorHelper( tile.xCoord + 0.5, tile.yCoord + 0.5, tile.zCoord + 0.5 ); from = from.addVector( s.offsetX * 0.501, s.offsetY * 0.501, s.offsetZ * 0.501 ); @@ -1038,17 +999,17 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - if ( te == null ) + if( te == null ) continue; - if ( te instanceof IInterfaceHost ) + if( te instanceof IInterfaceHost ) { try { - if ( ((IInterfaceHost) te).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) + if( ( (IInterfaceHost) te ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) continue; } - catch (GridAccessException e) + catch( GridAccessException e ) { continue; } @@ -1056,47 +1017,46 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn Item item = Item.getItemFromBlock( blk ); - if ( item == null ) + if( item == null ) { return blk.getUnlocalizedName(); } ItemStack what = new ItemStack( item, 1, blk.getDamageValue( w, tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ) ); - if ( te instanceof ICraftingMachine || InventoryAdaptor.getAdaptor( te, s.getOpposite() ) != null ) + if( te instanceof ICraftingMachine || InventoryAdaptor.getAdaptor( te, s.getOpposite() ) != null ) { - if ( te instanceof IInventory && ((IInventory) te).getSizeInventory() == 0 ) + if( te instanceof IInventory && ( (IInventory) te ).getSizeInventory() == 0 ) continue; - if ( te instanceof ISidedInventory ) + if( te instanceof ISidedInventory ) { - int[] sides = ((ISidedInventory) te).getAccessibleSlotsFromSide( s.getOpposite().ordinal() ); + int[] sides = ( (ISidedInventory) te ).getAccessibleSlotsFromSide( s.getOpposite().ordinal() ); - if ( sides == null || sides.length == 0 ) + if( sides == null || sides.length == 0 ) continue; } try { - if ( mop != null && !badBlocks.contains( blk ) ) + if( mop != null && !badBlocks.contains( blk ) ) { - if ( mop.blockX == te.xCoord && mop.blockY == te.yCoord && mop.blockZ == te.zCoord ) + if( mop.blockX == te.xCoord && mop.blockY == te.yCoord && mop.blockZ == te.zCoord ) { ItemStack g = blk.getPickBlock( mop, w, te.xCoord, te.yCoord, te.zCoord, null ); - if ( g != null ) + if( g != null ) what = g; } } } - catch (Throwable t) + catch( Throwable t ) { badBlocks.add( blk ); // nope! } - if ( what.getItem() != null ) + if( what.getItem() != null ) return what.getUnlocalizedName(); } - } return "Nothing"; @@ -1105,7 +1065,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn public long getSortValue() { TileEntity te = this.iHost.getTileEntity(); - return (te.zCoord << 24) ^ (te.xCoord << 8) ^ te.yCoord; + return ( te.zCoord << 24 ) ^ ( te.xCoord << 8 ) ^ te.yCoord; } public void initialize() @@ -1120,7 +1080,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn } @Override - public void setPriority(int newValue) + public void setPriority( int newValue ) { this.priority = newValue; this.markDirty(); @@ -1129,9 +1089,40 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn { this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // :P } } + + + class InterfaceInventory extends MEMonitorIInventory + { + + public InterfaceInventory( DualityInterface tileInterface ) + { + super( new AdaptorIInventory( tileInterface.storage ) ); + this.mySource = new MachineSource( DualityInterface.this.iHost ); + } + + @Override + public IAEItemStack injectItems( IAEItemStack input, Actionable type, BaseActionSource src ) + { + if( interfaceRequest ) + return input; + + return super.injectItems( input, type, src ); + } + + @Override + public IAEItemStack extractItems( IAEItemStack request, Actionable type, BaseActionSource src ) + { + if( interfaceRequest ) + return null; + + return super.extractItems( request, type, src ); + } + } + + } diff --git a/src/main/java/appeng/helpers/IContainerCraftingPacket.java b/src/main/java/appeng/helpers/IContainerCraftingPacket.java index b4be37061..5f4714018 100644 --- a/src/main/java/appeng/helpers/IContainerCraftingPacket.java +++ b/src/main/java/appeng/helpers/IContainerCraftingPacket.java @@ -18,12 +18,14 @@ package appeng.helpers; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import appeng.api.networking.IGridNode; import appeng.api.networking.security.BaseActionSource; + public interface IContainerCraftingPacket { @@ -34,9 +36,10 @@ public interface IContainerCraftingPacket /** * @param string name of inventory + * * @return the inventory of the part/tile by name. */ - IInventory getInventoryByName(String string); + IInventory getInventoryByName( String string ); /** * @return who are we? @@ -52,5 +55,4 @@ public interface IContainerCraftingPacket * @return array of view cells */ ItemStack[] getViewCells(); - } diff --git a/src/main/java/appeng/helpers/ICustomCollision.java b/src/main/java/appeng/helpers/ICustomCollision.java index ee9091de4..b7142ed82 100644 --- a/src/main/java/appeng/helpers/ICustomCollision.java +++ b/src/main/java/appeng/helpers/ICustomCollision.java @@ -18,15 +18,17 @@ package appeng.helpers; + import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; + public interface ICustomCollision { - Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity thePlayer, boolean b); + Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity thePlayer, boolean b ); - void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e); + void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ); } diff --git a/src/main/java/appeng/helpers/ICustomNameObject.java b/src/main/java/appeng/helpers/ICustomNameObject.java index 0bdb32484..c499e18b6 100644 --- a/src/main/java/appeng/helpers/ICustomNameObject.java +++ b/src/main/java/appeng/helpers/ICustomNameObject.java @@ -18,11 +18,11 @@ package appeng.helpers; + public interface ICustomNameObject { String getCustomName(); boolean hasCustomName(); - } diff --git a/src/main/java/appeng/helpers/IInterfaceHost.java b/src/main/java/appeng/helpers/IInterfaceHost.java index 079e6d138..3ca913298 100644 --- a/src/main/java/appeng/helpers/IInterfaceHost.java +++ b/src/main/java/appeng/helpers/IInterfaceHost.java @@ -18,6 +18,7 @@ package appeng.helpers; + import java.util.EnumSet; import net.minecraft.tileentity.TileEntity; @@ -27,6 +28,7 @@ import appeng.api.implementations.IUpgradeableHost; import appeng.api.networking.crafting.ICraftingProvider; import appeng.api.networking.crafting.ICraftingRequester; + public interface IInterfaceHost extends ICraftingProvider, IUpgradeableHost, ICraftingRequester { diff --git a/src/main/java/appeng/helpers/IMouseWheelItem.java b/src/main/java/appeng/helpers/IMouseWheelItem.java index 5f3963e07..cc223005d 100644 --- a/src/main/java/appeng/helpers/IMouseWheelItem.java +++ b/src/main/java/appeng/helpers/IMouseWheelItem.java @@ -18,11 +18,12 @@ package appeng.helpers; + import net.minecraft.item.ItemStack; + public interface IMouseWheelItem { - void onWheel(ItemStack is, boolean up); - + void onWheel( ItemStack is, boolean up ); } diff --git a/src/main/java/appeng/helpers/IPriorityHost.java b/src/main/java/appeng/helpers/IPriorityHost.java index 37a3d1061..083fd8ca4 100644 --- a/src/main/java/appeng/helpers/IPriorityHost.java +++ b/src/main/java/appeng/helpers/IPriorityHost.java @@ -18,6 +18,7 @@ package appeng.helpers; + public interface IPriorityHost { @@ -29,6 +30,5 @@ public interface IPriorityHost /** * set new priority */ - void setPriority(int newValue); - + void setPriority( int newValue ); } diff --git a/src/main/java/appeng/helpers/InventoryAction.java b/src/main/java/appeng/helpers/InventoryAction.java index 4a35272c8..5076b85ee 100644 --- a/src/main/java/appeng/helpers/InventoryAction.java +++ b/src/main/java/appeng/helpers/InventoryAction.java @@ -18,6 +18,7 @@ package appeng.helpers; + public enum InventoryAction { // standard vanilla mechanics. diff --git a/src/main/java/appeng/helpers/LocationRotation.java b/src/main/java/appeng/helpers/LocationRotation.java index 426a87c92..f6f77ffc0 100644 --- a/src/main/java/appeng/helpers/LocationRotation.java +++ b/src/main/java/appeng/helpers/LocationRotation.java @@ -18,11 +18,13 @@ package appeng.helpers; + import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; import appeng.api.util.IOrientable; + public class LocationRotation implements IOrientable { @@ -31,7 +33,8 @@ public class LocationRotation implements IOrientable final int y; final int z; - public LocationRotation(IBlockAccess world, int x, int y, int z) { + public LocationRotation( IBlockAccess world, int x, int y, int z ) + { this.w = world; this.x = x; this.y = y; @@ -39,9 +42,17 @@ public class LocationRotation implements IOrientable } @Override - public void setOrientation(ForgeDirection Forward, ForgeDirection Up) + public boolean canBeRotated() { + return false; + } + @Override + public ForgeDirection getForward() + { + if( this.getUp().offsetY == 0 ) + return ForgeDirection.UP; + return ForgeDirection.SOUTH; } @Override @@ -52,16 +63,8 @@ public class LocationRotation implements IOrientable } @Override - public ForgeDirection getForward() + public void setOrientation( ForgeDirection Forward, ForgeDirection Up ) { - if ( this.getUp().offsetY == 0 ) - return ForgeDirection.UP; - return ForgeDirection.SOUTH; - } - @Override - public boolean canBeRotated() - { - return false; } } diff --git a/src/main/java/appeng/helpers/MetaRotation.java b/src/main/java/appeng/helpers/MetaRotation.java index 1066dabcd..c84784219 100644 --- a/src/main/java/appeng/helpers/MetaRotation.java +++ b/src/main/java/appeng/helpers/MetaRotation.java @@ -18,12 +18,14 @@ package appeng.helpers; + import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import appeng.api.util.IOrientable; + public class MetaRotation implements IOrientable { @@ -32,7 +34,8 @@ public class MetaRotation implements IOrientable final int y; final int z; - public MetaRotation(IBlockAccess world, int x, int y, int z) { + public MetaRotation( IBlockAccess world, int x, int y, int z ) + { this.w = world; this.x = x; this.y = y; @@ -40,12 +43,17 @@ public class MetaRotation implements IOrientable } @Override - public void setOrientation(ForgeDirection Forward, ForgeDirection Up) + public boolean canBeRotated() { - if ( this.w instanceof World ) - ((World) this.w).setBlockMetadataWithNotify( this.x, this.y, this.z, Up.ordinal(), 1 + 2 ); - else - throw new RuntimeException( this.w.getClass().getName() + " received, expected World" ); + return true; + } + + @Override + public ForgeDirection getForward() + { + if( this.getUp().offsetY == 0 ) + return ForgeDirection.UP; + return ForgeDirection.SOUTH; } @Override @@ -55,16 +63,11 @@ public class MetaRotation implements IOrientable } @Override - public ForgeDirection getForward() + public void setOrientation( ForgeDirection Forward, ForgeDirection Up ) { - if ( this.getUp().offsetY == 0 ) - return ForgeDirection.UP; - return ForgeDirection.SOUTH; - } - - @Override - public boolean canBeRotated() - { - return true; + if( this.w instanceof World ) + ( (World) this.w ).setBlockMetadataWithNotify( this.x, this.y, this.z, Up.ordinal(), 1 + 2 ); + else + throw new RuntimeException( this.w.getClass().getName() + " received, expected World" ); } } diff --git a/src/main/java/appeng/helpers/MultiCraftingTracker.java b/src/main/java/appeng/helpers/MultiCraftingTracker.java index b8291c927..54a4caa89 100644 --- a/src/main/java/appeng/helpers/MultiCraftingTracker.java +++ b/src/main/java/appeng/helpers/MultiCraftingTracker.java @@ -18,14 +18,15 @@ package appeng.helpers; + import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; -import com.google.common.collect.ImmutableSet; - import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; +import com.google.common.collect.ImmutableSet; + import appeng.api.AEApi; import appeng.api.networking.IGrid; import appeng.api.networking.crafting.ICraftingGrid; @@ -37,6 +38,7 @@ import appeng.api.storage.data.IAEItemStack; import appeng.parts.automation.NonNullArrayIterator; import appeng.util.InventoryAdaptor; + public class MultiCraftingTracker { @@ -46,27 +48,50 @@ public class MultiCraftingTracker Future[] jobs = null; ICraftingLink[] links = null; - public MultiCraftingTracker(ICraftingRequester o, int size) { + public MultiCraftingTracker( ICraftingRequester o, int size ) + { this.owner = o; this.size = size; } - public void readFromNBT(NBTTagCompound extra) + public void readFromNBT( NBTTagCompound extra ) { - for (int x = 0; x < this.size; x++) + for( int x = 0; x < this.size; x++ ) { NBTTagCompound link = extra.getCompoundTag( "links-" + x ); - if ( link != null && !link.hasNoTags() ) + if( link != null && !link.hasNoTags() ) this.setLink( x, AEApi.instance().storage().loadCraftingLink( link, this.owner ) ); } } - public void writeToNBT(NBTTagCompound extra) + void setLink( int slot, ICraftingLink l ) { - for (int x = 0; x < this.size; x++) + if( this.links == null ) + this.links = new ICraftingLink[this.size]; + + this.links[slot] = l; + + boolean hasStuff = false; + for( int x = 0; x < this.links.length; x++ ) + { + ICraftingLink g = this.links[x]; + + if( g == null || g.isCanceled() || g.isDone() ) + this.links[x] = null; + else + hasStuff = true; + } + + if( !hasStuff ) + this.links = null; + } + + public void writeToNBT( NBTTagCompound extra ) + { + for( int x = 0; x < this.size; x++ ) { ICraftingLink link = this.getLink( x ); - if ( link != null ) + if( link != null ) { NBTTagCompound ln = new NBTTagCompound(); link.writeToNBT( ln ); @@ -75,42 +100,50 @@ public class MultiCraftingTracker } } - public boolean handleCrafting(int x, long itemToCraft, IAEItemStack ais, InventoryAdaptor d, World w, IGrid g, ICraftingGrid cg, BaseActionSource mySrc) + ICraftingLink getLink( int slot ) { - if ( ais != null && d.simulateAdd( ais.getItemStack() ) == null ) + if( this.links == null ) + return null; + + return this.links[slot]; + } + + public boolean handleCrafting( int x, long itemToCraft, IAEItemStack ais, InventoryAdaptor d, World w, IGrid g, ICraftingGrid cg, BaseActionSource mySrc ) + { + if( ais != null && d.simulateAdd( ais.getItemStack() ) == null ) { Future craftingJob = this.getJob( x ); - if ( this.getLink( x ) != null ) + if( this.getLink( x ) != null ) { return false; } - else if ( craftingJob != null ) + else if( craftingJob != null ) { ICraftingJob job = null; try { - if ( craftingJob.isDone() ) + if( craftingJob.isDone() ) job = craftingJob.get(); - if ( job != null ) + if( job != null ) { this.setJob( x, null ); this.setLink( x, cg.submitJob( job, this.owner, null, false, mySrc ) ); return true; } } - catch (InterruptedException e) + catch( InterruptedException e ) { // :P } - catch (ExecutionException e) + catch( ExecutionException e ) { // :P } } else { - if ( this.getLink( x ) == null ) + if( this.getLink( x ) == null ) { IAEItemStack aisC = ais.copy(); aisC.setStackSize( itemToCraft ); @@ -121,79 +154,49 @@ public class MultiCraftingTracker return false; } - ICraftingLink getLink(int slot) + Future getJob( int slot ) { - if ( this.links == null ) - return null; - - return this.links[slot]; - } - - void setLink(int slot, ICraftingLink l) - { - if ( this.links == null ) - this.links = new ICraftingLink[this.size]; - - this.links[slot] = l; - - boolean hasStuff = false; - for (int x = 0; x < this.links.length; x++) - { - ICraftingLink g = this.links[x]; - - if ( g == null || g.isCanceled() || g.isDone() ) - this.links[x] = null; - else - hasStuff = true; - } - - if ( !hasStuff ) - this.links = null; - } - - Future getJob(int slot) - { - if ( this.jobs == null ) + if( this.jobs == null ) return null; return this.jobs[slot]; } - void setJob(int slot, Future l) + void setJob( int slot, Future l ) { - if ( this.jobs == null ) + if( this.jobs == null ) this.jobs = new Future[this.size]; this.jobs[slot] = l; boolean hasStuff = false; - for (Future job : this.jobs) + for( Future job : this.jobs ) { - if ( job != null ) + if( job != null ) { hasStuff = true; } } - if ( !hasStuff ) + if( !hasStuff ) this.jobs = null; } public ImmutableSet getRequestedJobs() { - if ( this.links == null ) + if( this.links == null ) return ImmutableSet.of(); return ImmutableSet.copyOf( new NonNullArrayIterator( this.links ) ); } - public void jobStateChange(ICraftingLink link) + public void jobStateChange( ICraftingLink link ) { - if ( this.links != null ) + if( this.links != null ) { - for (int x = 0; x < this.links.length; x++) + for( int x = 0; x < this.links.length; x++ ) { - if ( this.links[x] == link ) + if( this.links[x] == link ) { this.setLink( x, null ); return; @@ -202,13 +205,13 @@ public class MultiCraftingTracker } } - public int getSlot(ICraftingLink link) + public int getSlot( ICraftingLink link ) { - if ( this.links != null ) + if( this.links != null ) { - for (int x = 0; x < this.links.length; x++) + for( int x = 0; x < this.links.length; x++ ) { - if ( this.links[x] == link ) + if( this.links[x] == link ) return x; } } @@ -218,22 +221,22 @@ public class MultiCraftingTracker public void cancel() { - if ( this.links != null ) + if( this.links != null ) { - for (ICraftingLink l : this.links) + for( ICraftingLink l : this.links ) { - if ( l != null ) + if( l != null ) l.cancel(); } this.links = null; } - if ( this.jobs != null ) + if( this.jobs != null ) { - for (Future l : this.jobs) + for( Future l : this.jobs ) { - if ( l != null ) + if( l != null ) l.cancel( true ); } @@ -241,7 +244,7 @@ public class MultiCraftingTracker } } - public boolean isBusy(int slot) + public boolean isBusy( int slot ) { return this.getLink( slot ) != null || this.getJob( slot ) != null; } diff --git a/src/main/java/appeng/helpers/NullRotation.java b/src/main/java/appeng/helpers/NullRotation.java index 342b4cabc..bcb9df73d 100644 --- a/src/main/java/appeng/helpers/NullRotation.java +++ b/src/main/java/appeng/helpers/NullRotation.java @@ -18,27 +18,24 @@ package appeng.helpers; + import net.minecraftforge.common.util.ForgeDirection; import appeng.api.util.IOrientable; + public class NullRotation implements IOrientable { - public NullRotation() { - - } - - @Override - public void setOrientation(ForgeDirection Forward, ForgeDirection Up) + public NullRotation() { } @Override - public ForgeDirection getUp() + public boolean canBeRotated() { - return ForgeDirection.UP; + return false; } @Override @@ -48,8 +45,14 @@ public class NullRotation implements IOrientable } @Override - public boolean canBeRotated() + public ForgeDirection getUp() { - return false; + return ForgeDirection.UP; + } + + @Override + public void setOrientation( ForgeDirection Forward, ForgeDirection Up ) + { + } } diff --git a/src/main/java/appeng/helpers/PatternHelper.java b/src/main/java/appeng/helpers/PatternHelper.java index 1ba6725fa..92a378452 100644 --- a/src/main/java/appeng/helpers/PatternHelper.java +++ b/src/main/java/appeng/helpers/PatternHelper.java @@ -41,113 +41,30 @@ import appeng.util.ItemSorters; import appeng.util.Platform; import appeng.util.item.AEItemStack; + public class PatternHelper implements ICraftingPatternDetails, Comparable { final ItemStack patternItem; - private final IAEItemStack pattern; - final InventoryCrafting crafting = new InventoryCrafting( new ContainerNull(), 3, 3 ); final InventoryCrafting testFrame = new InventoryCrafting( new ContainerNull(), 3, 3 ); - final ItemStack correctOutput; final IRecipe standardRecipe; - final IAEItemStack[] condensedInputs; final IAEItemStack[] condensedOutputs; final IAEItemStack[] inputs; final IAEItemStack[] outputs; - final boolean isCrafting; - public int priority = 0; - - static class TestLookup - { - - final int slot; - final int ref; - final int hash; - - public TestLookup(int slot, ItemStack i) - { - this( slot, i.getItem(), i.getItemDamage() ); - } - - public TestLookup(int slot, Item item, int dmg) - { - this.slot = slot; - this.ref = (dmg << Platform.DEF_OFFSET) | (Item.getIdFromItem( item ) & 0xffff); - int offset = 3 * slot; - this.hash = (this.ref << offset) | (this.ref >> (offset + 32)); - } - - @Override - public int hashCode() - { - return this.hash; - } - - @Override - public boolean equals(Object obj) - { - final boolean equality; - - if ( obj instanceof TestLookup ) - { - TestLookup b = (TestLookup) obj; - equality = b.slot == this.slot && b.ref == this.ref; - } - else - { - equality = false; - } - - return equality; - } - - } - - enum TestStatus - { - ACCEPT, DECLINE, TEST - } - final HashSet failCache = new HashSet(); final HashSet passCache = new HashSet(); + private final IAEItemStack pattern; + public int priority = 0; - private void markItemAs(int slotIndex, ItemStack i, TestStatus b) - { - if ( b == TestStatus.TEST || i.hasTagCompound() ) - return; - - (b == TestStatus.ACCEPT ? this.passCache : this.failCache).add( new TestLookup( slotIndex, i ) ); - } - - private TestStatus getStatus(int slotIndex, ItemStack i) - { - if ( this.crafting.getStackInSlot( slotIndex ) == null ) - return i == null ? TestStatus.ACCEPT : TestStatus.DECLINE; - - if ( i == null ) - return TestStatus.DECLINE; - - if ( i.hasTagCompound() ) - return TestStatus.TEST; - - if ( this.passCache.contains( new TestLookup( slotIndex, i ) ) ) - return TestStatus.ACCEPT; - - if ( this.failCache.contains( new TestLookup( slotIndex, i ) ) ) - return TestStatus.DECLINE; - - return TestStatus.TEST; - } - - public PatternHelper(ItemStack is, World w) + public PatternHelper( ItemStack is, World w ) { NBTTagCompound encodedValue = is.getTagCompound(); - if ( encodedValue == null ) + if( encodedValue == null ) throw new RuntimeException( "No pattern here!" ); NBTTagList inTag = encodedValue.getTagList( "in", 10 ); @@ -159,12 +76,12 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable in = new ArrayList(); List out = new ArrayList(); - for (int x = 0; x < inTag.tagCount(); x++) + for( int x = 0; x < inTag.tagCount(); x++ ) { ItemStack gs = ItemStack.loadItemStackFromNBT( inTag.getCompoundTagAt( x ) ); this.crafting.setInventorySlotContents( x, gs ); - if ( gs != null && (!this.isCrafting || !gs.hasTagCompound()) ) + if( gs != null && ( !this.isCrafting || !gs.hasTagCompound() ) ) { this.markItemAs( x, gs, TestStatus.ACCEPT ); } @@ -173,10 +90,10 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable tmpOutputs = new HashMap(); - for (IAEItemStack io : this.outputs) + for( IAEItemStack io : this.outputs ) { - if ( io == null ) + if( io == null ) continue; IAEItemStack g = tmpOutputs.get( io ); - if ( g == null ) + if( g == null ) tmpOutputs.put( io, io.copy() ); else g.add( io ); } HashMap tmpInputs = new HashMap(); - for (IAEItemStack io : this.inputs) + for( IAEItemStack io : this.inputs ) { - if ( io == null ) + if( io == null ) continue; IAEItemStack g = tmpInputs.get( io ); - if ( g == null ) + if( g == null ) tmpInputs.put( io, io.copy() ); else g.add( io ); } - if ( tmpOutputs.isEmpty() || tmpInputs.isEmpty() ) + if( tmpOutputs.isEmpty() || tmpInputs.isEmpty() ) throw new RuntimeException( "No pattern here!" ); int offset = 0; this.condensedInputs = new IAEItemStack[tmpInputs.size()]; - for (IAEItemStack io : tmpInputs.values()) + for( IAEItemStack io : tmpInputs.values() ) { this.condensedInputs[offset] = io; offset++; @@ -239,44 +156,58 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable 0 ) - return this.outputs[0].getItemStack(); - - return null; - } - - @Override - public boolean canSubstitute() - { - return false; - } - @Override public boolean isCraftable() { @@ -335,18 +242,6 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable 0 ) + return this.outputs[0].getItemStack(); + + return null; + } + + private TestStatus getStatus( int slotIndex, ItemStack i ) + { + if( this.crafting.getStackInSlot( slotIndex ) == null ) + return i == null ? TestStatus.ACCEPT : TestStatus.DECLINE; + + if( i == null ) + return TestStatus.DECLINE; + + if( i.hasTagCompound() ) + return TestStatus.TEST; + + if( this.passCache.contains( new TestLookup( slotIndex, i ) ) ) + return TestStatus.ACCEPT; + + if( this.failCache.contains( new TestLookup( slotIndex, i ) ) ) + return TestStatus.DECLINE; + + return TestStatus.TEST; + } + + @Override + public int getPriority() + { + return this.priority; + } + + @Override + public void setPriority( int priority ) + { + this.priority = priority; + } + + @Override + public int compareTo( PatternHelper o ) { return ItemSorters.compareInt( o.priority, this.priority ); } @@ -371,28 +328,67 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable> ( offset + 32 ) ); + } + + @Override + public int hashCode() + { + return this.hash; + } + + @Override + public boolean equals( Object obj ) + { + final boolean equality; + + if( obj instanceof TestLookup ) + { + TestLookup b = (TestLookup) obj; + equality = b.slot == this.slot && b.ref == this.ref; + } + else + { + equality = false; + } + + return equality; + } + } + + @Override + public boolean equals( Object obj ) + { + if( obj == null ) return false; - if ( this.getClass() != obj.getClass() ) + if( this.getClass() != obj.getClass() ) return false; PatternHelper other = (PatternHelper) obj; - if ( this.pattern != null && other.pattern != null ) + if( this.pattern != null && other.pattern != null ) return this.pattern.equals( other.pattern ); return false; } - - @Override - public void setPriority(int priority) - { - this.priority = priority; - } - - @Override - public int getPriority() - { - return this.priority; - } } diff --git a/src/main/java/appeng/helpers/PlayerSecurityWrapper.java b/src/main/java/appeng/helpers/PlayerSecurityWrapper.java index 031070018..a91a90c30 100644 --- a/src/main/java/appeng/helpers/PlayerSecurityWrapper.java +++ b/src/main/java/appeng/helpers/PlayerSecurityWrapper.java @@ -18,23 +18,26 @@ package appeng.helpers; + import java.util.EnumSet; import java.util.HashMap; import appeng.api.config.SecurityPermissions; import appeng.api.networking.security.ISecurityRegistry; + public class PlayerSecurityWrapper implements ISecurityRegistry { final HashMap> target; - public PlayerSecurityWrapper(HashMap> playerPerms) { + public PlayerSecurityWrapper( HashMap> playerPerms ) + { this.target = playerPerms; } @Override - public void addPlayer(int PlayerID, EnumSet permissions) + public void addPlayer( int PlayerID, EnumSet permissions ) { this.target.put( PlayerID, permissions ); } diff --git a/src/main/java/appeng/helpers/Splotch.java b/src/main/java/appeng/helpers/Splotch.java index 96aae4f5d..3f6987b5f 100644 --- a/src/main/java/appeng/helpers/Splotch.java +++ b/src/main/java/appeng/helpers/Splotch.java @@ -18,6 +18,7 @@ package appeng.helpers; + import io.netty.buffer.ByteBuf; import net.minecraft.util.Vec3; @@ -25,23 +26,30 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.util.AEColor; + public class Splotch { - public Splotch(AEColor col, boolean lit, ForgeDirection side, Vec3 Pos) { + final public ForgeDirection side; + final public boolean lumen; + final public AEColor color; + final private int pos; + + public Splotch( AEColor col, boolean lit, ForgeDirection side, Vec3 Pos ) + { this.color = col; this.lumen = lit; double x; double y; - if ( side == ForgeDirection.SOUTH || side == ForgeDirection.NORTH ) + if( side == ForgeDirection.SOUTH || side == ForgeDirection.NORTH ) { x = Pos.xCoord; y = Pos.yCoord; } - else if ( side == ForgeDirection.UP || side == ForgeDirection.DOWN ) + else if( side == ForgeDirection.UP || side == ForgeDirection.DOWN ) { x = Pos.xCoord; y = Pos.zCoord; @@ -53,48 +61,44 @@ public class Splotch y = Pos.zCoord; } - int a = (int) (x * 0xF); - int b = (int) (y * 0xF); - this.pos = a | (b << 4); + int a = (int) ( x * 0xF ); + int b = (int) ( y * 0xF ); + this.pos = a | ( b << 4 ); this.side = side; } - public Splotch(ByteBuf data) { + public Splotch( ByteBuf data ) + { this.pos = data.readByte(); int val = data.readByte(); this.side = ForgeDirection.getOrientation( val & 0x07 ); - this.color = AEColor.values()[(val >> 3) & 0x0F]; - this.lumen = ((val >> 7) & 0x01) > 0; + this.color = AEColor.values()[( val >> 3 ) & 0x0F]; + this.lumen = ( ( val >> 7 ) & 0x01 ) > 0; } - public void writeToStream(ByteBuf stream) + public void writeToStream( ByteBuf stream ) { stream.writeByte( this.pos ); - int val = this.side.ordinal() | (this.color.ordinal() << 3) | (this.lumen ? 0x80 : 0x00); + int val = this.side.ordinal() | ( this.color.ordinal() << 3 ) | ( this.lumen ? 0x80 : 0x00 ); stream.writeByte( val ); } - final private int pos; - final public ForgeDirection side; - final public boolean lumen; - final public AEColor color; - public float x() { - return (this.pos & 0x0f) / 15.0f; + return ( this.pos & 0x0f ) / 15.0f; } public float y() { - return ((this.pos >> 4) & 0x0f) / 15.0f; + return ( ( this.pos >> 4 ) & 0x0f ) / 15.0f; } public int getSeed() { - int val = this.side.ordinal() | (this.color.ordinal() << 3) | (this.lumen ? 0x80 : 0x00); + int val = this.side.ordinal() | ( this.color.ordinal() << 3 ) | ( this.lumen ? 0x80 : 0x00 ); return Math.abs( this.pos + val ); } } diff --git a/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java b/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java index f4f978778..0a0a5e135 100644 --- a/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java +++ b/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java @@ -18,6 +18,7 @@ package appeng.helpers; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -49,29 +50,23 @@ import appeng.api.util.DimensionalCoord; import appeng.api.util.IConfigManager; import appeng.tile.networking.TileWireless; + public class WirelessTerminalGuiObject implements IPortableCell, IActionHost { + public final ItemStack effectiveItem; final IWirelessTermHandler wth; final String encryptionKey; - + final EntityPlayer myPlayer; IGrid targetGrid; IStorageGrid sg; IMEMonitor itemStorage; IWirelessAccessPoint myWap; - double sqRange = Double.MAX_VALUE; double myRange = Double.MAX_VALUE; - final EntityPlayer myPlayer; - public final ItemStack effectiveItem; - - public double getRange() + public WirelessTerminalGuiObject( IWirelessTermHandler wh, ItemStack is, EntityPlayer ep, World w, int x, int y, int z ) { - return this.myRange; - } - - public WirelessTerminalGuiObject(IWirelessTermHandler wh, ItemStack is, EntityPlayer ep, World w, int x, int y, int z) { this.encryptionKey = wh.getEncryptionKey( is ); this.effectiveItem = is; this.myPlayer = ep; @@ -84,90 +79,36 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost long encKey = Long.parseLong( this.encryptionKey ); obj = AEApi.instance().registries().locatable().getLocatableBy( encKey ); } - catch (NumberFormatException err) + catch( NumberFormatException err ) { // :P } - if ( obj instanceof IGridHost ) + if( obj instanceof IGridHost ) { - IGridNode n = ((IGridHost) obj).getGridNode( ForgeDirection.UNKNOWN ); - if ( n != null ) + IGridNode n = ( (IGridHost) obj ).getGridNode( ForgeDirection.UNKNOWN ); + if( n != null ) { this.targetGrid = n.getGrid(); - if ( this.targetGrid != null ) + if( this.targetGrid != null ) { this.sg = this.targetGrid.getCache( IStorageGrid.class ); - if ( this.sg != null ) + if( this.sg != null ) this.itemStorage = this.sg.getItemInventory(); } } } } - public boolean rangeCheck() + public double getRange() { - this.sqRange = this.myRange = Double.MAX_VALUE; - - if ( this.targetGrid != null && this.itemStorage != null ) - { - if ( this.myWap != null ) - { - if ( this.myWap.getGrid() == this.targetGrid ) - { - if ( this.testWap( this.myWap ) ) - return true; - } - return false; - } - - IMachineSet tw = this.targetGrid.getMachines( TileWireless.class ); - - this.myWap = null; - - for (IGridNode n : tw) - { - IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); - if ( this.testWap( wap ) ) - this.myWap = wap; - } - - return this.myWap != null; - } - return false; - } - - private boolean testWap(IWirelessAccessPoint wap) - { - double rangeLimit = wap.getRange(); - rangeLimit *= rangeLimit; - - DimensionalCoord dc = wap.getLocation(); - - if ( dc.getWorld() == this.myPlayer.worldObj ) - { - double offX = dc.x - this.myPlayer.posX; - double offY = dc.y - this.myPlayer.posY; - double offZ = dc.z - this.myPlayer.posZ; - - double r = offX * offX + offY * offY + offZ * offZ; - if ( r < rangeLimit && this.sqRange > r ) - { - if ( wap.isActive() ) - { - this.sqRange = r; - this.myRange = Math.sqrt( r ); - return true; - } - } - } - return false; + return this.myRange; } @Override public IMEMonitor getItemInventory() { - if ( this.sg == null ) + if( this.sg == null ) return null; return this.sg.getItemInventory(); } @@ -175,29 +116,29 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost @Override public IMEMonitor getFluidInventory() { - if ( this.sg == null ) + if( this.sg == null ) return null; return this.sg.getFluidInventory(); } @Override - public void addListener(IMEMonitorHandlerReceiver l, Object verificationToken) + public void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ) { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) this.itemStorage.addListener( l, verificationToken ); } @Override - public void removeListener(IMEMonitorHandlerReceiver l) + public void removeListener( IMEMonitorHandlerReceiver l ) { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) this.itemStorage.removeListener( l ); } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.getAvailableItems( out ); return out; } @@ -205,7 +146,7 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost @Override public IItemList getStorageList() { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.getStorageList(); return null; } @@ -213,23 +154,23 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost @Override public AccessRestriction getAccess() { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.getAccess(); return AccessRestriction.NO_ACCESS; } @Override - public boolean isPrioritized(IAEItemStack input) + public boolean isPrioritized( IAEItemStack input ) { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.isPrioritized( input ); return false; } @Override - public boolean canAccept(IAEItemStack input) + public boolean canAccept( IAEItemStack input ) { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.canAccept( input ); return false; } @@ -237,7 +178,7 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost @Override public int getPriority() { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.getPriority(); return 0; } @@ -245,23 +186,29 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost @Override public int getSlot() { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.getSlot(); return 0; } @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable type, BaseActionSource src) + public boolean validForPass( int i ) { - if ( this.itemStorage != null ) + return this.itemStorage.validForPass( i ); + } + + @Override + public IAEItemStack injectItems( IAEItemStack input, Actionable type, BaseActionSource src ) + { + if( this.itemStorage != null ) return this.itemStorage.injectItems( input, type, src ); return input; } @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) + public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.extractItems( request, mode, src ); return null; } @@ -269,17 +216,17 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost @Override public StorageChannel getChannel() { - if ( this.itemStorage != null ) + if( this.itemStorage != null ) return this.itemStorage.getChannel(); return StorageChannel.ITEMS; } @Override - public double extractAEPower(double amt, Actionable mode, PowerMultiplier usePowerMultiplier) + public double extractAEPower( double amt, Actionable mode, PowerMultiplier usePowerMultiplier ) { - if ( this.wth != null && this.effectiveItem != null ) + if( this.wth != null && this.effectiveItem != null ) { - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) { return this.wth.hasPower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; } @@ -301,13 +248,13 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost } @Override - public IGridNode getGridNode(ForgeDirection dir) + public IGridNode getGridNode( ForgeDirection dir ) { return this.getActionableNode(); } @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.NONE; } @@ -322,15 +269,67 @@ public class WirelessTerminalGuiObject implements IPortableCell, IActionHost public IGridNode getActionableNode() { this.rangeCheck(); - if ( this.myWap != null ) + if( this.myWap != null ) return this.myWap.getActionableNode(); return null; } - @Override - public boolean validForPass(int i) + public boolean rangeCheck() { - return this.itemStorage.validForPass( i ); + this.sqRange = this.myRange = Double.MAX_VALUE; + + if( this.targetGrid != null && this.itemStorage != null ) + { + if( this.myWap != null ) + { + if( this.myWap.getGrid() == this.targetGrid ) + { + if( this.testWap( this.myWap ) ) + return true; + } + return false; + } + + IMachineSet tw = this.targetGrid.getMachines( TileWireless.class ); + + this.myWap = null; + + for( IGridNode n : tw ) + { + IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); + if( this.testWap( wap ) ) + this.myWap = wap; + } + + return this.myWap != null; + } + return false; } + private boolean testWap( IWirelessAccessPoint wap ) + { + double rangeLimit = wap.getRange(); + rangeLimit *= rangeLimit; + + DimensionalCoord dc = wap.getLocation(); + + if( dc.getWorld() == this.myPlayer.worldObj ) + { + double offX = dc.x - this.myPlayer.posX; + double offY = dc.y - this.myPlayer.posY; + double offZ = dc.z - this.myPlayer.posZ; + + double r = offX * offX + offY * offY + offZ * offZ; + if( r < rangeLimit && this.sqRange > r ) + { + if( wap.isActive() ) + { + this.sqRange = r; + this.myRange = Math.sqrt( r ); + return true; + } + } + } + return false; + } } diff --git a/src/main/java/appeng/hooks/AETrading.java b/src/main/java/appeng/hooks/AETrading.java index f6c26b0fd..64c05e967 100644 --- a/src/main/java/appeng/hooks/AETrading.java +++ b/src/main/java/appeng/hooks/AETrading.java @@ -18,6 +18,7 @@ package appeng.hooks; + import java.util.Random; import net.minecraft.entity.passive.EntityVillager; @@ -38,55 +39,34 @@ import appeng.api.definitions.IMaterials; public class AETrading implements IVillageTradeHandler { - private void addToList(MerchantRecipeList l, ItemStack a, ItemStack b) + @Override + public void manipulateTradesForVillager( EntityVillager villager, MerchantRecipeList recipeList, Random random ) { - if ( a.stackSize < 1 ) - a.stackSize = 1; - if ( b.stackSize < 1 ) - b.stackSize = 1; + final IMaterials materials = AEApi.instance().definitions().materials(); - if ( a.stackSize > a.getMaxStackSize() ) - a.stackSize = a.getMaxStackSize(); - if ( b.stackSize > b.getMaxStackSize() ) - b.stackSize = b.getMaxStackSize(); + this.addMerchant( recipeList, materials.silicon(), 1, random, 2 ); + this.addMerchant( recipeList, materials.certusQuartzCrystal(), 2, random, 4 ); + this.addMerchant( recipeList, materials.certusQuartzDust(), 1, random, 3 ); - l.add( new MerchantRecipe( a, b ) ); + this.addTrade( recipeList, materials.certusQuartzDust(), materials.certusQuartzCrystal(), random, 2 ); } - private void addTrade(MerchantRecipeList list, IItemDefinition inputDefinition, IItemDefinition outputDefinition, Random rand, int conversionVariance) + private void addMerchant( MerchantRecipeList list, IItemDefinition item, int emera, Random rand, int greed ) { - final Optional maybeInputStack = inputDefinition.maybeStack( 1 ); - final Optional maybeOutputStack = outputDefinition.maybeStack( 1 ); - - if ( maybeInputStack.isPresent() && maybeOutputStack.isPresent() ) - { - // Sell - ItemStack inputStack = maybeInputStack.get().copy(); - ItemStack outputStack = maybeOutputStack.get().copy(); - - inputStack.stackSize = 1 + (Math.abs( rand.nextInt() ) % (1 + conversionVariance)); - outputStack.stackSize = 1; - - this.addToList( list, inputStack, outputStack ); - } - } - - private void addMerchant(MerchantRecipeList list, IItemDefinition item, int emera, Random rand, int greed) - { - for ( ItemStack itemStack : item.maybeStack( 1 ).asSet() ) + for( ItemStack itemStack : item.maybeStack( 1 ).asSet() ) { // Sell ItemStack from = itemStack.copy(); ItemStack to = new ItemStack( Items.emerald ); - int multiplier = (Math.abs( rand.nextInt() ) % 6); - final int emeraldCost = emera + (Math.abs( rand.nextInt() ) % greed) - multiplier; + int multiplier = ( Math.abs( rand.nextInt() ) % 6 ); + final int emeraldCost = emera + ( Math.abs( rand.nextInt() ) % greed ) - multiplier; int mood = rand.nextInt() % 2; from.stackSize = multiplier + mood; to.stackSize = multiplier * emeraldCost - mood; - if ( to.stackSize < 0 ) + if( to.stackSize < 0 ) { from.stackSize -= to.stackSize; to.stackSize -= to.stackSize; @@ -104,16 +84,36 @@ public class AETrading implements IVillageTradeHandler } } - @Override - public void manipulateTradesForVillager(EntityVillager villager, MerchantRecipeList recipeList, Random random) + private void addTrade( MerchantRecipeList list, IItemDefinition inputDefinition, IItemDefinition outputDefinition, Random rand, int conversionVariance ) { - final IMaterials materials = AEApi.instance().definitions().materials(); + final Optional maybeInputStack = inputDefinition.maybeStack( 1 ); + final Optional maybeOutputStack = outputDefinition.maybeStack( 1 ); - this.addMerchant( recipeList, materials.silicon(), 1, random, 2 ); - this.addMerchant( recipeList, materials.certusQuartzCrystal(), 2, random, 4 ); - this.addMerchant( recipeList, materials.certusQuartzDust(), 1, random, 3 ); + if( maybeInputStack.isPresent() && maybeOutputStack.isPresent() ) + { + // Sell + ItemStack inputStack = maybeInputStack.get().copy(); + ItemStack outputStack = maybeOutputStack.get().copy(); - this.addTrade( recipeList, materials.certusQuartzDust(), materials.certusQuartzCrystal(), random, 2 ); + inputStack.stackSize = 1 + ( Math.abs( rand.nextInt() ) % ( 1 + conversionVariance ) ); + outputStack.stackSize = 1; + + this.addToList( list, inputStack, outputStack ); + } } + private void addToList( MerchantRecipeList l, ItemStack a, ItemStack b ) + { + if( a.stackSize < 1 ) + a.stackSize = 1; + if( b.stackSize < 1 ) + b.stackSize = 1; + + if( a.stackSize > a.getMaxStackSize() ) + a.stackSize = a.getMaxStackSize(); + if( b.stackSize > b.getMaxStackSize() ) + b.stackSize = b.getMaxStackSize(); + + l.add( new MerchantRecipe( a, b ) ); + } } diff --git a/src/main/java/appeng/hooks/CompassManager.java b/src/main/java/appeng/hooks/CompassManager.java index c2fa6f3b9..f798bc8c3 100644 --- a/src/main/java/appeng/hooks/CompassManager.java +++ b/src/main/java/appeng/hooks/CompassManager.java @@ -18,16 +18,64 @@ package appeng.hooks; + import java.util.HashMap; import java.util.Iterator; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketCompassRequest; + public class CompassManager { public static final CompassManager INSTANCE = new CompassManager(); + final HashMap requests = new HashMap(); + + public void postResult( long attunement, int x, int y, int z, CompassResult result ) + { + CompassRequest r = new CompassRequest( attunement, x, y, z ); + this.requests.put( r, result ); + } + + public CompassResult getCompassDirection( long attunement, int x, int y, int z ) + { + long now = System.currentTimeMillis(); + + Iterator i = this.requests.values().iterator(); + while( i.hasNext() ) + { + CompassResult res = i.next(); + long diff = now - res.time; + if( diff > 20000 ) + i.remove(); + } + + CompassRequest r = new CompassRequest( attunement, x, y, z ); + CompassResult res = this.requests.get( r ); + + if( res == null ) + { + res = new CompassResult( false, true, 0 ); + this.requests.put( r, res ); + this.requestUpdate( r ); + } + else if( now - res.time > 1000 * 3 ) + { + if( !res.requested ) + { + res.requested = true; + this.requestUpdate( r ); + } + } + + return res; + } + + private void requestUpdate( CompassRequest r ) + { + NetworkHandler.instance.sendToServer( new PacketCompassRequest( r.attunement, r.cx, r.cz, r.cdy ) ); + } static class CompassRequest { @@ -39,12 +87,13 @@ public class CompassManager final int cdy; final int cz; - public CompassRequest(long attunement, int x, int y, int z) { + public CompassRequest( long attunement, int x, int y, int z ) + { this.attunement = attunement; this.cx = x >> 4; this.cdy = y >> 5; this.cz = z >> 4; - this.hash = ((Integer) this.cx).hashCode() ^ ((Integer) this.cdy).hashCode() ^ ((Integer) this.cz).hashCode() ^ ((Long) attunement).hashCode(); + this.hash = ( (Integer) this.cx ).hashCode() ^ ( (Integer) this.cdy ).hashCode() ^ ( (Integer) this.cz ).hashCode() ^ ( (Long) attunement ).hashCode(); } @Override @@ -54,63 +103,14 @@ public class CompassManager } @Override - public boolean equals(Object obj) + public boolean equals( Object obj ) { - if ( obj == null ) + if( obj == null ) return false; - if ( this.getClass() != obj.getClass() ) + if( this.getClass() != obj.getClass() ) return false; CompassRequest other = (CompassRequest) obj; return this.attunement == other.attunement && this.cx == other.cx && this.cdy == other.cdy && this.cz == other.cz; } - } - - final HashMap requests = new HashMap(); - - public void postResult(long attunement, int x, int y, int z, CompassResult result) - { - CompassRequest r = new CompassRequest( attunement, x, y, z ); - this.requests.put( r, result ); - } - - public CompassResult getCompassDirection(long attunement, int x, int y, int z) - { - long now = System.currentTimeMillis(); - - Iterator i = this.requests.values().iterator(); - while (i.hasNext()) - { - CompassResult res = i.next(); - long diff = now - res.time; - if ( diff > 20000 ) - i.remove(); - } - - CompassRequest r = new CompassRequest( attunement, x, y, z ); - CompassResult res = this.requests.get( r ); - - if ( res == null ) - { - res = new CompassResult( false, true, 0 ); - this.requests.put( r, res ); - this.requestUpdate( r ); - } - else if ( now - res.time > 1000 * 3 ) - { - if ( !res.requested ) - { - res.requested = true; - this.requestUpdate( r ); - } - } - - return res; - } - - private void requestUpdate(CompassRequest r) - { - NetworkHandler.instance.sendToServer( new PacketCompassRequest( r.attunement, r.cx, r.cz, r.cdy ) ); - } - } diff --git a/src/main/java/appeng/hooks/CompassResult.java b/src/main/java/appeng/hooks/CompassResult.java index c3d1ec9ae..ead5e0829 100644 --- a/src/main/java/appeng/hooks/CompassResult.java +++ b/src/main/java/appeng/hooks/CompassResult.java @@ -18,6 +18,7 @@ package appeng.hooks; + public class CompassResult { @@ -28,11 +29,11 @@ public class CompassResult public boolean requested = false; - public CompassResult(boolean hasResult, boolean spin, double rad) { + public CompassResult( boolean hasResult, boolean spin, double rad ) + { this.hasResult = hasResult; this.spin = spin; this.rad = rad; this.time = System.currentTimeMillis(); } - } diff --git a/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java b/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java index ca60d4411..78da9a607 100644 --- a/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java +++ b/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java @@ -18,6 +18,7 @@ package appeng.hooks; + import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; import net.minecraft.dispenser.IBlockSource; @@ -27,22 +28,21 @@ import net.minecraft.world.World; import appeng.entity.EntityTinyTNTPrimed; + final public class DispenserBehaviorTinyTNT extends BehaviorDefaultDispenseItem { @Override - protected ItemStack dispenseStack(IBlockSource dispenser, ItemStack dispensedItem) + protected ItemStack dispenseStack( IBlockSource dispenser, ItemStack dispensedItem ) { EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); World world = dispenser.getWorld(); int i = dispenser.getXInt() + enumfacing.getFrontOffsetX(); int j = dispenser.getYInt() + enumfacing.getFrontOffsetY(); int k = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); - EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( world, i + 0.5F, j + 0.5F, - k + 0.5F, null ); + EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( world, i + 0.5F, j + 0.5F, k + 0.5F, null ); world.spawnEntityInWorld( primedTinyTNTEntity ); --dispensedItem.stackSize; return dispensedItem; } - } diff --git a/src/main/java/appeng/hooks/DispenserBlockTool.java b/src/main/java/appeng/hooks/DispenserBlockTool.java index 34fd7121e..3f2d84bbf 100644 --- a/src/main/java/appeng/hooks/DispenserBlockTool.java +++ b/src/main/java/appeng/hooks/DispenserBlockTool.java @@ -18,6 +18,7 @@ package appeng.hooks; + import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; import net.minecraft.dispenser.IBlockSource; @@ -29,20 +30,21 @@ import net.minecraft.world.WorldServer; import appeng.util.Platform; + final public class DispenserBlockTool extends BehaviorDefaultDispenseItem { @Override - protected ItemStack dispenseStack(IBlockSource dispenser, ItemStack dispensedItem) + protected ItemStack dispenseStack( IBlockSource dispenser, ItemStack dispensedItem ) { Item i = dispensedItem.getItem(); - if ( i instanceof IBlockTool ) + if( i instanceof IBlockTool ) { EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); IBlockTool tm = (IBlockTool) i; World w = dispenser.getWorld(); - if ( w instanceof WorldServer ) + if( w instanceof WorldServer ) { int x = dispenser.getXInt() + enumfacing.getFrontOffsetX(); int y = dispenser.getYInt() + enumfacing.getFrontOffsetY(); diff --git a/src/main/java/appeng/hooks/DispenserMatterCannon.java b/src/main/java/appeng/hooks/DispenserMatterCannon.java index c1b984660..4da9d3cb2 100644 --- a/src/main/java/appeng/hooks/DispenserMatterCannon.java +++ b/src/main/java/appeng/hooks/DispenserMatterCannon.java @@ -18,6 +18,7 @@ package appeng.hooks; + import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; import net.minecraft.dispenser.IBlockSource; @@ -32,27 +33,28 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.items.tools.powered.ToolMassCannon; import appeng.util.Platform; + final public class DispenserMatterCannon extends BehaviorDefaultDispenseItem { @Override - protected ItemStack dispenseStack(IBlockSource dispenser, ItemStack dispensedItem) + protected ItemStack dispenseStack( IBlockSource dispenser, ItemStack dispensedItem ) { Item i = dispensedItem.getItem(); - if ( i instanceof ToolMassCannon ) + if( i instanceof ToolMassCannon ) { EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); ForgeDirection dir = ForgeDirection.UNKNOWN; - for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) { - if ( enumfacing.getFrontOffsetX() == d.offsetX && enumfacing.getFrontOffsetY() == d.offsetY && enumfacing.getFrontOffsetZ() == d.offsetZ ) + if( enumfacing.getFrontOffsetX() == d.offsetX && enumfacing.getFrontOffsetY() == d.offsetY && enumfacing.getFrontOffsetZ() == d.offsetZ ) dir = d; } ToolMassCannon tm = (ToolMassCannon) i; World w = dispenser.getWorld(); - if ( w instanceof WorldServer ) + if( w instanceof WorldServer ) { EntityPlayer p = Platform.getPlayer( (WorldServer) w ); Platform.configurePlayer( p, dir, dispenser.getBlockTileEntity() ); diff --git a/src/main/java/appeng/hooks/IBlockTool.java b/src/main/java/appeng/hooks/IBlockTool.java index e6caea5e2..9bff76a99 100644 --- a/src/main/java/appeng/hooks/IBlockTool.java +++ b/src/main/java/appeng/hooks/IBlockTool.java @@ -18,13 +18,14 @@ package appeng.hooks; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; + public interface IBlockTool { - boolean onItemUse(ItemStack dispensedItem, EntityPlayer player, World w, int x, int y, int z, int ordinal, float hitX, float hitY, float hitZ); - + boolean onItemUse( ItemStack dispensedItem, EntityPlayer player, World w, int x, int y, int z, int ordinal, float hitX, float hitY, float hitZ ); } diff --git a/src/main/java/appeng/hooks/TickHandler.java b/src/main/java/appeng/hooks/TickHandler.java index 6fe2cb579..5e5a620b8 100644 --- a/src/main/java/appeng/hooks/TickHandler.java +++ b/src/main/java/appeng/hooks/TickHandler.java @@ -57,111 +57,64 @@ import appeng.me.NetworkList; import appeng.tile.AEBaseTile; import appeng.util.Platform; + public class TickHandler { - static class HandlerRep - { - - public Queue tiles = new LinkedList(); - - public Collection networks = new NetworkList(); - - public void clear() - { - this.tiles = new LinkedList(); - this.networks = new NetworkList(); - } - - } - public static final TickHandler INSTANCE = new TickHandler(); - - final private WeakHashMap> callQueue = new WeakHashMap>(); final Queue serverQueue = new LinkedList(); - + final Multimap craftingJobs = LinkedListMultimap.create(); + final private WeakHashMap> callQueue = new WeakHashMap>(); final private HandlerRep server = new HandlerRep(); final private HandlerRep client = new HandlerRep(); - - static public class PlayerColor - { - - public final AEColor myColor; - protected final int myEntity; - protected int ticksLeft; - - public PacketPaintedEntity getPacket() - { - return new PacketPaintedEntity( this.myEntity, this.myColor, this.ticksLeft ); - } - - public PlayerColor(int id, AEColor col, int ticks) { - this.myEntity = id; - this.myColor = col; - this.ticksLeft = ticks; - } - - } - final private HashMap cliPlayerColors = new HashMap(); final private HashMap srvPlayerColors = new HashMap(); + CableRenderMode crm = CableRenderMode.Standard; public HashMap getPlayerColors() { - if ( Platform.isServer() ) + if( Platform.isServer() ) return this.srvPlayerColors; return this.cliPlayerColors; } - private void tickColors(HashMap playerSet) + public void addCallable( World w, Callable c ) { - Iterator i = playerSet.values().iterator(); - while (i.hasNext()) - { - PlayerColor pc = i.next(); - if ( pc.ticksLeft <= 0 ) - i.remove(); - pc.ticksLeft--; - } - } - - HandlerRep getRepo() - { - if ( Platform.isServer() ) - return this.server; - return this.client; - } - - public void addCallable(World w, Callable c) - { - if ( w == null ) + if( w == null ) this.serverQueue.add( c ); else { Queue queue = this.callQueue.get( w ); - if ( queue == null ) + if( queue == null ) this.callQueue.put( w, queue = new LinkedList() ); queue.add( c ); } } - public void addInit(AEBaseTile tile) + public void addInit( AEBaseTile tile ) { - if ( Platform.isServer() ) // for no there is no reason to care about this on the client... + if( Platform.isServer() ) // for no there is no reason to care about this on the client... this.getRepo().tiles.add( tile ); } - public void addNetwork(Grid grid) + HandlerRep getRepo() { - if ( Platform.isServer() ) // for no there is no reason to care about this on the client... + if( Platform.isServer() ) + return this.server; + return this.client; + } + + public void addNetwork( Grid grid ) + { + if( Platform.isServer() ) // for no there is no reason to care about this on the client... this.getRepo().networks.add( grid ); } - public void removeNetwork(Grid grid) + public void removeNetwork( Grid grid ) { - if ( Platform.isServer() ) // for no there is no reason to care about this on the client... + if( Platform.isServer() ) // for no there is no reason to care about this on the client... this.getRepo().networks.remove( grid ); } @@ -176,70 +129,68 @@ public class TickHandler } @SubscribeEvent - public void unloadWorld(WorldEvent.Unload ev) + public void unloadWorld( WorldEvent.Unload ev ) { - if ( Platform.isServer() ) // for no there is no reason to care about this on the client... + if( Platform.isServer() ) // for no there is no reason to care about this on the client... { LinkedList toDestroy = new LinkedList(); - for (Grid g : this.getRepo().networks) + for( Grid g : this.getRepo().networks ) { - for (IGridNode n : g.getNodes()) + for( IGridNode n : g.getNodes() ) { - if ( n.getWorld() == ev.world ) + if( n.getWorld() == ev.world ) toDestroy.add( n ); } } - for (IGridNode n : toDestroy) + for( IGridNode n : toDestroy ) n.destroy(); } } @SubscribeEvent - public void onChunkLoad(ChunkEvent.Load load) + public void onChunkLoad( ChunkEvent.Load load ) { - for (Object te : load.getChunk().chunkTileEntityMap.values()) + for( Object te : load.getChunk().chunkTileEntityMap.values() ) { - if ( te instanceof AEBaseTile ) + if( te instanceof AEBaseTile ) { - ((AEBaseTile) te).onChunkLoad(); + ( (AEBaseTile) te ).onChunkLoad(); } } } - CableRenderMode crm = CableRenderMode.Standard; - @SubscribeEvent - public void onTick(TickEvent ev) + public void onTick( TickEvent ev ) { - if ( ev.type == Type.CLIENT && ev.phase == Phase.START ) + if( ev.type == Type.CLIENT && ev.phase == Phase.START ) { this.tickColors( this.cliPlayerColors ); - EntityFloatingItem.ageStatic = (EntityFloatingItem.ageStatic + 1) % 60000; + EntityFloatingItem.ageStatic = ( EntityFloatingItem.ageStatic + 1 ) % 60000; CableRenderMode currentMode = AEApi.instance().partHelper().getCableRenderMode(); - if ( currentMode != this.crm ) + if( currentMode != this.crm ) { this.crm = currentMode; CommonHelper.proxy.triggerUpdates(); } } - if ( ev.type == Type.WORLD && ev.phase == Phase.END ) + if( ev.type == Type.WORLD && ev.phase == Phase.END ) { WorldTickEvent wte = (WorldTickEvent) ev; - synchronized (this.craftingJobs) + synchronized( this.craftingJobs ) { Collection jobSet = this.craftingJobs.get( wte.world ); - if ( !jobSet.isEmpty() ) + if( !jobSet.isEmpty() ) { int simTime = Math.max( 1, AEConfig.instance.craftingCalculationTimePerTick / jobSet.size() ); Iterator i = jobSet.iterator(); - while (i.hasNext()) + while( i.hasNext() ) { CraftingJob cj = i.next(); - if ( !cj.simulateFor( simTime ) ) + if( !cj.simulateFor( simTime ) ) i.remove(); } } @@ -247,20 +198,20 @@ public class TickHandler } // for no there is no reason to care about this on the client... - else if ( ev.type == Type.SERVER && ev.phase == Phase.END ) + else if( ev.type == Type.SERVER && ev.phase == Phase.END ) { this.tickColors( this.srvPlayerColors ); // ready tiles. HandlerRep repo = this.getRepo(); - while (!repo.tiles.isEmpty()) + while( !repo.tiles.isEmpty() ) { AEBaseTile bt = repo.tiles.poll(); - if ( !bt.isInvalid() ) + if( !bt.isInvalid() ) bt.onReady(); } // tick networks. - for (Grid g : this.getRepo().networks) + for( Grid g : this.getRepo().networks ) g.update(); // cross world queue. @@ -268,30 +219,42 @@ public class TickHandler } // world synced queue(s) - if ( ev.type == Type.WORLD && ev.phase == Phase.START ) + if( ev.type == Type.WORLD && ev.phase == Phase.START ) { - this.processQueue( this.callQueue.get( ((WorldTickEvent) ev).world ) ); + this.processQueue( this.callQueue.get( ( (WorldTickEvent) ev ).world ) ); } } - private void processQueue(Queue queue) + private void tickColors( HashMap playerSet ) { - if ( queue == null ) + Iterator i = playerSet.values().iterator(); + while( i.hasNext() ) + { + PlayerColor pc = i.next(); + if( pc.ticksLeft <= 0 ) + i.remove(); + pc.ticksLeft--; + } + } + + private void processQueue( Queue queue ) + { + if( queue == null ) return; Stopwatch sw = Stopwatch.createStarted(); Callable c = null; - while ((c = queue.poll()) != null) + while( ( c = queue.poll() ) != null ) { try { c.call(); - if ( sw.elapsed( TimeUnit.MILLISECONDS ) > 50 ) + if( sw.elapsed( TimeUnit.MILLISECONDS ) > 50 ) break; } - catch (Exception e) + catch( Exception e ) { AELog.error( e ); } @@ -302,14 +265,46 @@ public class TickHandler // AELog.info( "processQueue Time: " + time + "ms" ); } - final Multimap craftingJobs = LinkedListMultimap.create(); - - public void registerCraftingSimulation(World world, CraftingJob craftingJob) + public void registerCraftingSimulation( World world, CraftingJob craftingJob ) { - synchronized (this.craftingJobs) + synchronized( this.craftingJobs ) { this.craftingJobs.put( world, craftingJob ); } } + static class HandlerRep + { + + public Queue tiles = new LinkedList(); + + public Collection networks = new NetworkList(); + + public void clear() + { + this.tiles = new LinkedList(); + this.networks = new NetworkList(); + } + } + + + static public class PlayerColor + { + + public final AEColor myColor; + protected final int myEntity; + protected int ticksLeft; + + public PlayerColor( int id, AEColor col, int ticks ) + { + this.myEntity = id; + this.myColor = col; + this.ticksLeft = ticks; + } + + public PacketPaintedEntity getPacket() + { + return new PacketPaintedEntity( this.myEntity, this.myColor, this.ticksLeft ); + } + } } diff --git a/src/main/java/appeng/integration/BaseModule.java b/src/main/java/appeng/integration/BaseModule.java index 159314188..ce5c7db78 100644 --- a/src/main/java/appeng/integration/BaseModule.java +++ b/src/main/java/appeng/integration/BaseModule.java @@ -18,17 +18,18 @@ package appeng.integration; -public abstract class BaseModule implements IIntegrationModule { + +public abstract class BaseModule implements IIntegrationModule +{ protected void testClassExistence( Class clz ) { - clz.isInstance(this); + clz.isInstance( this ); } @Override public abstract void init() throws Throwable; @Override - public abstract void postInit(); - + public abstract void postInit(); } diff --git a/src/main/java/appeng/integration/IIntegrationModule.java b/src/main/java/appeng/integration/IIntegrationModule.java index 37dd08c7a..b320efd9a 100644 --- a/src/main/java/appeng/integration/IIntegrationModule.java +++ b/src/main/java/appeng/integration/IIntegrationModule.java @@ -18,11 +18,11 @@ package appeng.integration; + public interface IIntegrationModule { void init() throws Throwable; void postInit(); - } diff --git a/src/main/java/appeng/integration/IntegrationNode.java b/src/main/java/appeng/integration/IntegrationNode.java index 51da5c525..ea8133854 100644 --- a/src/main/java/appeng/integration/IntegrationNode.java +++ b/src/main/java/appeng/integration/IntegrationNode.java @@ -27,23 +27,23 @@ import appeng.api.exceptions.ModNotInstalled; import appeng.core.AEConfig; import appeng.core.AELog; + public class IntegrationNode { + final String displayName; + final String modID; + final IntegrationType shortName; IntegrationStage state = IntegrationStage.PRE_INIT; IntegrationStage failedStage = IntegrationStage.PRE_INIT; Throwable exception = null; - - final String displayName; - final String modID; - - final IntegrationType shortName; String name = null; Class classValue = null; Object instance; IIntegrationModule mod = null; - public IntegrationNode(String displayName, String modID, IntegrationType shortName, String name) { + public IntegrationNode( String displayName, String modID, IntegrationType shortName, String name ) + { this.displayName = displayName; this.shortName = shortName; this.modID = modID; @@ -56,61 +56,66 @@ public class IntegrationNode return this.shortName.name() + ':' + this.state.name(); } - void Call(IntegrationStage stage) + public boolean isActive() { - if ( this.state != IntegrationStage.FAILED ) + if( this.state == IntegrationStage.PRE_INIT ) + this.Call( IntegrationStage.PRE_INIT ); + + return this.state != IntegrationStage.FAILED; + } + + void Call( IntegrationStage stage ) + { + if( this.state != IntegrationStage.FAILED ) { - if ( this.state.ordinal() > stage.ordinal() ) + if( this.state.ordinal() > stage.ordinal() ) return; try { - switch (stage) + switch( stage ) { - case PRE_INIT: + case PRE_INIT: - boolean enabled = this.modID == null || Loader.isModLoaded( this.modID ); + boolean enabled = this.modID == null || Loader.isModLoaded( this.modID ); - AEConfig.instance - .addCustomCategoryComment( - "ModIntegration", - "Valid Values are 'AUTO', 'ON', or 'OFF' - defaults to 'AUTO' ; Suggested that you leave this alone unless your experiencing an issue, or wish to disable the integration for a reason." ); - String Mode = AEConfig.instance.get( "ModIntegration", this.displayName.replace( " ", "" ), "AUTO" ).getString(); + AEConfig.instance.addCustomCategoryComment( "ModIntegration", "Valid Values are 'AUTO', 'ON', or 'OFF' - defaults to 'AUTO' ; Suggested that you leave this alone unless your experiencing an issue, or wish to disable the integration for a reason." ); + String Mode = AEConfig.instance.get( "ModIntegration", this.displayName.replace( " ", "" ), "AUTO" ).getString(); - if ( Mode.toUpperCase().equals( "ON" ) ) - enabled = true; - if ( Mode.toUpperCase().equals( "OFF" ) ) - enabled = false; + if( Mode.toUpperCase().equals( "ON" ) ) + enabled = true; + if( Mode.toUpperCase().equals( "OFF" ) ) + enabled = false; - if ( enabled ) - { - this.classValue = this.getClass().getClassLoader().loadClass( this.name ); - this.mod = (IIntegrationModule) this.classValue.getConstructor().newInstance(); - Field f = this.classValue.getField( "instance" ); - f.set( this.classValue, this.instance = this.mod ); - } - else - throw new ModNotInstalled( this.modID ); + if( enabled ) + { + this.classValue = this.getClass().getClassLoader().loadClass( this.name ); + this.mod = (IIntegrationModule) this.classValue.getConstructor().newInstance(); + Field f = this.classValue.getField( "instance" ); + f.set( this.classValue, this.instance = this.mod ); + } + else + throw new ModNotInstalled( this.modID ); - this.state = IntegrationStage.INIT; + this.state = IntegrationStage.INIT; - break; - case INIT: - this.mod.init(); - this.state = IntegrationStage.POST_INIT; + break; + case INIT: + this.mod.init(); + this.state = IntegrationStage.POST_INIT; - break; - case POST_INIT: - this.mod.postInit(); - this.state = IntegrationStage.READY; + break; + case POST_INIT: + this.mod.postInit(); + this.state = IntegrationStage.READY; - break; - case FAILED: - default: - break; + break; + case FAILED: + default: + break; } } - catch (Throwable t) + catch( Throwable t ) { this.failedStage = stage; this.exception = t; @@ -118,12 +123,12 @@ public class IntegrationNode } } - if ( stage == IntegrationStage.POST_INIT ) + if( stage == IntegrationStage.POST_INIT ) { - if ( this.state == IntegrationStage.FAILED ) + if( this.state == IntegrationStage.FAILED ) { AELog.info( this.displayName + " - Integration Disabled" ); - if ( !(this.exception instanceof ModNotInstalled) ) + if( !( this.exception instanceof ModNotInstalled ) ) AELog.integration( this.exception ); } else @@ -132,13 +137,4 @@ public class IntegrationNode } } } - - public boolean isActive() - { - if ( this.state == IntegrationStage.PRE_INIT ) - this.Call( IntegrationStage.PRE_INIT ); - - return this.state != IntegrationStage.FAILED; - } - } diff --git a/src/main/java/appeng/integration/IntegrationRegistry.java b/src/main/java/appeng/integration/IntegrationRegistry.java index 135698948..eb387e854 100644 --- a/src/main/java/appeng/integration/IntegrationRegistry.java +++ b/src/main/java/appeng/integration/IntegrationRegistry.java @@ -34,10 +34,10 @@ public enum IntegrationRegistry public void add( IntegrationType type ) { - if ( type.side == IntegrationSide.CLIENT && FMLLaunchHandler.side() == Side.SERVER ) + if( type.side == IntegrationSide.CLIENT && FMLLaunchHandler.side() == Side.SERVER ) return; - if ( type.side == IntegrationSide.SERVER && FMLLaunchHandler.side() == Side.CLIENT ) + if( type.side == IntegrationSide.SERVER && FMLLaunchHandler.side() == Side.CLIENT ) return; this.modules.add( new IntegrationNode( type.dspName, type.modID, type, "appeng.integration.modules." + type.name() ) ); @@ -45,16 +45,16 @@ public enum IntegrationRegistry public void init() { - for ( IntegrationNode node : this.modules ) + for( IntegrationNode node : this.modules ) node.Call( IntegrationStage.PRE_INIT ); - for ( IntegrationNode node : this.modules ) + for( IntegrationNode node : this.modules ) node.Call( IntegrationStage.INIT ); } public void postInit() { - for ( IntegrationNode node : this.modules ) + for( IntegrationNode node : this.modules ) node.Call( IntegrationStage.POST_INIT ); } @@ -62,9 +62,9 @@ public enum IntegrationRegistry { final StringBuilder builder = new StringBuilder( this.modules.size() * 3 ); - for ( IntegrationNode node : this.modules ) + for( IntegrationNode node : this.modules ) { - if ( builder.length() != 0 ) + if( builder.length() != 0 ) { builder.append( ", " ); } @@ -78,9 +78,9 @@ public enum IntegrationRegistry public boolean isEnabled( IntegrationType name ) { - for ( IntegrationNode node : this.modules ) + for( IntegrationNode node : this.modules ) { - if ( node.shortName == name ) + if( node.shortName == name ) return node.isActive(); } return false; @@ -88,9 +88,9 @@ public enum IntegrationRegistry public Object getInstance( IntegrationType name ) { - for ( IntegrationNode node : this.modules ) + for( IntegrationNode node : this.modules ) { - if ( node.shortName == name && node.isActive() ) + if( node.shortName == name && node.isActive() ) { return node.instance; } diff --git a/src/main/java/appeng/integration/IntegrationSide.java b/src/main/java/appeng/integration/IntegrationSide.java index 60ba21b97..25fd40a4d 100644 --- a/src/main/java/appeng/integration/IntegrationSide.java +++ b/src/main/java/appeng/integration/IntegrationSide.java @@ -18,6 +18,7 @@ package appeng.integration; + public enum IntegrationSide { CLIENT, SERVER, BOTH diff --git a/src/main/java/appeng/integration/IntegrationStage.java b/src/main/java/appeng/integration/IntegrationStage.java index 5b3162ea3..628cf5d4f 100644 --- a/src/main/java/appeng/integration/IntegrationStage.java +++ b/src/main/java/appeng/integration/IntegrationStage.java @@ -18,6 +18,7 @@ package appeng.integration; + public enum IntegrationStage { diff --git a/src/main/java/appeng/integration/IntegrationType.java b/src/main/java/appeng/integration/IntegrationType.java index 2797d02ed..099c9775d 100644 --- a/src/main/java/appeng/integration/IntegrationType.java +++ b/src/main/java/appeng/integration/IntegrationType.java @@ -18,55 +18,57 @@ package appeng.integration; + public enum IntegrationType { - IC2(IntegrationSide.BOTH, "Industrial Craft 2", "IC2"), + IC2( IntegrationSide.BOTH, "Industrial Craft 2", "IC2" ), - RotaryCraft(IntegrationSide.BOTH, "Rotary Craft", "RotaryCraft"), + RotaryCraft( IntegrationSide.BOTH, "Rotary Craft", "RotaryCraft" ), - RC(IntegrationSide.BOTH, "Railcraft", "Railcraft"), + RC( IntegrationSide.BOTH, "Railcraft", "Railcraft" ), - BC(IntegrationSide.BOTH, "BuildCraft", "BuildCraft|Silicon"), + BC( IntegrationSide.BOTH, "BuildCraft", "BuildCraft|Silicon" ), - MJ6(IntegrationSide.BOTH, "BuildCraft6 Power", null), + MJ6( IntegrationSide.BOTH, "BuildCraft6 Power", null ), - MJ5(IntegrationSide.BOTH, "BuildCraft5 Power", null), + MJ5( IntegrationSide.BOTH, "BuildCraft5 Power", null ), - RF(IntegrationSide.BOTH, "RedstoneFlux Power - Tiles", null), + RF( IntegrationSide.BOTH, "RedstoneFlux Power - Tiles", null ), - RFItem(IntegrationSide.BOTH, "RedstoneFlux Power - Items", null), + RFItem( IntegrationSide.BOTH, "RedstoneFlux Power - Items", null ), - MFR(IntegrationSide.BOTH, "Mine Factory Reloaded", "MineFactoryReloaded"), + MFR( IntegrationSide.BOTH, "Mine Factory Reloaded", "MineFactoryReloaded" ), - DSU(IntegrationSide.BOTH, "Deep Storage Unit", null), + DSU( IntegrationSide.BOTH, "Deep Storage Unit", null ), - FZ(IntegrationSide.BOTH, "Factorization", "factorization"), + FZ( IntegrationSide.BOTH, "Factorization", "factorization" ), - FMP(IntegrationSide.BOTH, "Forge MultiPart", "McMultipart"), + FMP( IntegrationSide.BOTH, "Forge MultiPart", "McMultipart" ), - RB(IntegrationSide.BOTH, "Rotatable Blocks", "RotatableBlocks"), + RB( IntegrationSide.BOTH, "Rotatable Blocks", "RotatableBlocks" ), - CLApi(IntegrationSide.BOTH, "Colored Lights Core", "coloredlightscore"), + CLApi( IntegrationSide.BOTH, "Colored Lights Core", "coloredlightscore" ), - Waila(IntegrationSide.BOTH, "Waila", "Waila"), + Waila( IntegrationSide.BOTH, "Waila", "Waila" ), - InvTweaks(IntegrationSide.CLIENT, "Inventory Tweaks", "inventorytweaks"), + InvTweaks( IntegrationSide.CLIENT, "Inventory Tweaks", "inventorytweaks" ), - NEI(IntegrationSide.CLIENT, "Not Enough Items", "NotEnoughItems"), + NEI( IntegrationSide.CLIENT, "Not Enough Items", "NotEnoughItems" ), - CraftGuide(IntegrationSide.CLIENT, "Craft Guide", "craftguide"), + CraftGuide( IntegrationSide.CLIENT, "Craft Guide", "craftguide" ), - Mekanism(IntegrationSide.BOTH, "Mekanism", "Mekanism"), + Mekanism( IntegrationSide.BOTH, "Mekanism", "Mekanism" ), - ImmibisMicroblocks(IntegrationSide.BOTH, "ImmibisMicroblocks", "ImmibisMicroblocks"), + ImmibisMicroblocks( IntegrationSide.BOTH, "ImmibisMicroblocks", "ImmibisMicroblocks" ), - BetterStorage(IntegrationSide.BOTH, "BetterStorage", "betterstorage" ); + BetterStorage( IntegrationSide.BOTH, "BetterStorage", "betterstorage" ); public final IntegrationSide side; public final String dspName; public final String modID; - IntegrationType( IntegrationSide side, String Name, String modid ) { + IntegrationType( IntegrationSide side, String Name, String modid ) + { this.side = side; this.dspName = Name; this.modID = modid; diff --git a/src/main/java/appeng/integration/abstraction/IBetterStorage.java b/src/main/java/appeng/integration/abstraction/IBetterStorage.java index d3a25c7ce..62de3a64e 100644 --- a/src/main/java/appeng/integration/abstraction/IBetterStorage.java +++ b/src/main/java/appeng/integration/abstraction/IBetterStorage.java @@ -18,15 +18,16 @@ package appeng.integration.abstraction; + import net.minecraftforge.common.util.ForgeDirection; import appeng.util.InventoryAdaptor; + public interface IBetterStorage { - boolean isStorageCrate(Object te); - - InventoryAdaptor getAdaptor(Object te, ForgeDirection d); + boolean isStorageCrate( Object te ); + InventoryAdaptor getAdaptor( Object te, ForgeDirection d ); } diff --git a/src/main/java/appeng/integration/abstraction/ICLApi.java b/src/main/java/appeng/integration/abstraction/ICLApi.java index 15dc0a5f0..d3184ecc4 100644 --- a/src/main/java/appeng/integration/abstraction/ICLApi.java +++ b/src/main/java/appeng/integration/abstraction/ICLApi.java @@ -18,11 +18,12 @@ package appeng.integration.abstraction; + import appeng.api.util.AEColor; + public interface ICLApi { - int colorLight(AEColor color, int light); - + int colorLight( AEColor color, int light ); } diff --git a/src/main/java/appeng/integration/abstraction/IDSU.java b/src/main/java/appeng/integration/abstraction/IDSU.java index 5f841f93e..66899f09e 100644 --- a/src/main/java/appeng/integration/abstraction/IDSU.java +++ b/src/main/java/appeng/integration/abstraction/IDSU.java @@ -18,15 +18,16 @@ package appeng.integration.abstraction; + import net.minecraft.tileentity.TileEntity; import appeng.api.storage.IMEInventory; + public interface IDSU { - IMEInventory getDSU(TileEntity te); - - boolean isDSU(TileEntity te); + IMEInventory getDSU( TileEntity te ); + boolean isDSU( TileEntity te ); } diff --git a/src/main/java/appeng/integration/abstraction/IFMP.java b/src/main/java/appeng/integration/abstraction/IFMP.java index 38d7d0f7a..62f1339a4 100644 --- a/src/main/java/appeng/integration/abstraction/IFMP.java +++ b/src/main/java/appeng/integration/abstraction/IFMP.java @@ -18,6 +18,7 @@ package appeng.integration.abstraction; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; @@ -26,15 +27,15 @@ import cpw.mods.fml.common.eventhandler.Event; import appeng.api.parts.IPartHost; import appeng.parts.CableBusContainer; + public interface IFMP { - IPartHost getOrCreateHost(TileEntity tile); + IPartHost getOrCreateHost( TileEntity tile ); - CableBusContainer getCableContainer(TileEntity te); + CableBusContainer getCableContainer( TileEntity te ); - void registerPassThrough(Class layerInterface); - - Event newFMPPacketEvent(EntityPlayerMP sender); + void registerPassThrough( Class layerInterface ); + Event newFMPPacketEvent( EntityPlayerMP sender ); } diff --git a/src/main/java/appeng/integration/abstraction/IFZ.java b/src/main/java/appeng/integration/abstraction/IFZ.java index 62e2c942b..372b52081 100644 --- a/src/main/java/appeng/integration/abstraction/IFZ.java +++ b/src/main/java/appeng/integration/abstraction/IFZ.java @@ -18,28 +18,29 @@ package appeng.integration.abstraction; + import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import appeng.api.storage.IMEInventory; + public interface IFZ { - ItemStack barrelGetItem(TileEntity te); + ItemStack barrelGetItem( TileEntity te ); - int barrelGetMaxItemCount(TileEntity te); + int barrelGetMaxItemCount( TileEntity te ); - int barrelGetItemCount(TileEntity te); + int barrelGetItemCount( TileEntity te ); - void setItemType(TileEntity te, ItemStack input); + void setItemType( TileEntity te, ItemStack input ); - void barrelSetCount(TileEntity te, int max); + void barrelSetCount( TileEntity te, int max ); - IMEInventory getFactorizationBarrel(TileEntity te); + IMEInventory getFactorizationBarrel( TileEntity te ); - boolean isBarrel(TileEntity te); - - void grinderRecipe(ItemStack is, ItemStack itemStack); + boolean isBarrel( TileEntity te ); + void grinderRecipe( ItemStack is, ItemStack itemStack ); } diff --git a/src/main/java/appeng/integration/abstraction/IForestry.java b/src/main/java/appeng/integration/abstraction/IForestry.java index 90d9c4443..816583c0d 100644 --- a/src/main/java/appeng/integration/abstraction/IForestry.java +++ b/src/main/java/appeng/integration/abstraction/IForestry.java @@ -18,11 +18,12 @@ package appeng.integration.abstraction; + import appeng.api.features.IItemComparisonProvider; + public interface IForestry { IItemComparisonProvider getGeneticsComparisonProvider(); - } \ No newline at end of file diff --git a/src/main/java/appeng/integration/abstraction/IGT.java b/src/main/java/appeng/integration/abstraction/IGT.java index 15c66727c..959f9dfc2 100644 --- a/src/main/java/appeng/integration/abstraction/IGT.java +++ b/src/main/java/appeng/integration/abstraction/IGT.java @@ -18,15 +18,16 @@ package appeng.integration.abstraction; + import net.minecraft.tileentity.TileEntity; import appeng.api.storage.IMEInventory; + public interface IGT { - boolean isQuantumChest(TileEntity te); - - IMEInventory getQuantumChest(TileEntity te); + boolean isQuantumChest( TileEntity te ); + IMEInventory getQuantumChest( TileEntity te ); } diff --git a/src/main/java/appeng/integration/abstraction/IIC2.java b/src/main/java/appeng/integration/abstraction/IIC2.java index 17fb6e7c8..655bc1093 100644 --- a/src/main/java/appeng/integration/abstraction/IIC2.java +++ b/src/main/java/appeng/integration/abstraction/IIC2.java @@ -18,18 +18,19 @@ package appeng.integration.abstraction; + import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; + public interface IIC2 { - void addToEnergyNet(TileEntity appEngTile); + void addToEnergyNet( TileEntity appEngTile ); - void removeFromEnergyNet(TileEntity appEngTile); + void removeFromEnergyNet( TileEntity appEngTile ); - ItemStack getItem(String string); - - void maceratorRecipe(ItemStack in, ItemStack out); + ItemStack getItem( String string ); + void maceratorRecipe( ItemStack in, ItemStack out ); } diff --git a/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java b/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java index 2036726a2..5d79e67ba 100644 --- a/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java +++ b/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java @@ -18,20 +18,22 @@ package appeng.integration.abstraction; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import appeng.api.parts.IPartHost; + public interface IImmibisMicroblocks { - IPartHost getOrCreateHost(EntityPlayer player, int side, TileEntity te); + IPartHost getOrCreateHost( EntityPlayer player, int side, TileEntity te ); /** * @param te to be left tile entity + * * @return true if this worked.. */ - boolean leaveParts(TileEntity te); - + boolean leaveParts( TileEntity te ); } diff --git a/src/main/java/appeng/integration/abstraction/IInvTweaks.java b/src/main/java/appeng/integration/abstraction/IInvTweaks.java index a1a16c180..e493123f9 100644 --- a/src/main/java/appeng/integration/abstraction/IInvTweaks.java +++ b/src/main/java/appeng/integration/abstraction/IInvTweaks.java @@ -18,11 +18,12 @@ package appeng.integration.abstraction; + import net.minecraft.item.ItemStack; + public interface IInvTweaks { - int compareItems(ItemStack i, ItemStack j); - + int compareItems( ItemStack i, ItemStack j ); } diff --git a/src/main/java/appeng/integration/abstraction/ILP.java b/src/main/java/appeng/integration/abstraction/ILP.java index ceb0d3e58..f1133494b 100644 --- a/src/main/java/appeng/integration/abstraction/ILP.java +++ b/src/main/java/appeng/integration/abstraction/ILP.java @@ -18,6 +18,7 @@ package appeng.integration.abstraction; + import java.util.List; import net.minecraft.item.ItemStack; @@ -25,25 +26,25 @@ import net.minecraft.tileentity.TileEntity; import appeng.api.storage.IMEInventory; + public interface ILP { - List getCraftedItems(TileEntity te); + List getCraftedItems( TileEntity te ); - List getProvidedItems(TileEntity te); + List getProvidedItems( TileEntity te ); - boolean isRequestPipe(TileEntity te); + boolean isRequestPipe( TileEntity te ); - List performRequest(TileEntity te, ItemStack wanted); + List performRequest( TileEntity te, ItemStack wanted ); - IMEInventory getInv(TileEntity te); + IMEInventory getInv( TileEntity te ); - Object getGetPowerPipe(TileEntity te); + Object getGetPowerPipe( TileEntity te ); - boolean isPowerSource(TileEntity tt); + boolean isPowerSource( TileEntity tt ); - boolean canUseEnergy(Object pp, int ceil, List providersToIgnore); - - boolean useEnergy(Object pp, int ceil, List providersToIgnore); + boolean canUseEnergy( Object pp, int ceil, List providersToIgnore ); + boolean useEnergy( Object pp, int ceil, List providersToIgnore ); } diff --git a/src/main/java/appeng/integration/abstraction/IMekanism.java b/src/main/java/appeng/integration/abstraction/IMekanism.java index cf1bf33e7..8f56d415c 100644 --- a/src/main/java/appeng/integration/abstraction/IMekanism.java +++ b/src/main/java/appeng/integration/abstraction/IMekanism.java @@ -18,13 +18,14 @@ package appeng.integration.abstraction; + import net.minecraft.item.ItemStack; + public interface IMekanism { - void addCrusherRecipe(ItemStack in, ItemStack out); - - void addEnrichmentChamberRecipe(ItemStack in, ItemStack out); + void addCrusherRecipe( ItemStack in, ItemStack out ); + void addEnrichmentChamberRecipe( ItemStack in, ItemStack out ); } diff --git a/src/main/java/appeng/integration/abstraction/INEI.java b/src/main/java/appeng/integration/abstraction/INEI.java index a47de6636..817ef8b42 100644 --- a/src/main/java/appeng/integration/abstraction/INEI.java +++ b/src/main/java/appeng/integration/abstraction/INEI.java @@ -18,14 +18,15 @@ package appeng.integration.abstraction; + import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.inventory.Slot; + public interface INEI { - void drawSlot(Slot s); - - RenderItem setItemRender(RenderItem renderItem); + void drawSlot( Slot s ); + RenderItem setItemRender( RenderItem renderItem ); } diff --git a/src/main/java/appeng/integration/abstraction/IRB.java b/src/main/java/appeng/integration/abstraction/IRB.java index 59b3f57fd..bcf07178b 100644 --- a/src/main/java/appeng/integration/abstraction/IRB.java +++ b/src/main/java/appeng/integration/abstraction/IRB.java @@ -18,13 +18,14 @@ package appeng.integration.abstraction; + import net.minecraft.tileentity.TileEntity; import appeng.api.util.IOrientable; + public interface IRB { - IOrientable getOrientable(TileEntity te); - + IOrientable getOrientable( TileEntity te ); } diff --git a/src/main/java/appeng/integration/abstraction/IRC.java b/src/main/java/appeng/integration/abstraction/IRC.java index ce9f6ed7d..857a5cc02 100644 --- a/src/main/java/appeng/integration/abstraction/IRC.java +++ b/src/main/java/appeng/integration/abstraction/IRC.java @@ -18,11 +18,12 @@ package appeng.integration.abstraction; + import net.minecraft.item.ItemStack; + public interface IRC { - void rockCrusher(ItemStack input, ItemStack output); - + void rockCrusher( ItemStack input, ItemStack output ); } diff --git a/src/main/java/appeng/integration/abstraction/ITE.java b/src/main/java/appeng/integration/abstraction/ITE.java index eb9375d84..7aca71e7d 100644 --- a/src/main/java/appeng/integration/abstraction/ITE.java +++ b/src/main/java/appeng/integration/abstraction/ITE.java @@ -18,19 +18,20 @@ package appeng.integration.abstraction; + import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; + public interface ITE { - void addPulverizerRecipe(int i, ItemStack blkQuartz, ItemStack blockDust); + void addPulverizerRecipe( int i, ItemStack blkQuartz, ItemStack blockDust ); - void addPulverizerRecipe(int i, ItemStack blkQuartzOre, ItemStack matQuartz, ItemStack matQuartzDust); + void addPulverizerRecipe( int i, ItemStack blkQuartzOre, ItemStack matQuartz, ItemStack matQuartzDust ); - boolean isPipe(TileEntity te, ForgeDirection opposite); - - ItemStack addItemsToPipe(TileEntity ad, ItemStack itemstack, ForgeDirection dir); + boolean isPipe( TileEntity te, ForgeDirection opposite ); + ItemStack addItemsToPipe( TileEntity ad, ItemStack itemstack, ForgeDirection dir ); } diff --git a/src/main/java/appeng/integration/modules/BC.java b/src/main/java/appeng/integration/modules/BC.java index 5606016e2..35ea38241 100644 --- a/src/main/java/appeng/integration/modules/BC.java +++ b/src/main/java/appeng/integration/modules/BC.java @@ -94,13 +94,13 @@ public final class BC extends BaseModule implements IBC @Override public boolean canAddItemsToPipe( TileEntity te, ItemStack is, ForgeDirection dir ) { - if ( is != null && te != null && te instanceof IInjectable ) + if( is != null && te != null && te instanceof IInjectable ) { IInjectable pt = (IInjectable) te; - if ( pt.canInjectItems( dir ) ) + if( pt.canInjectItems( dir ) ) { int amt = pt.injectItem( is, false, dir, null ); - if ( amt == is.stackSize ) + if( amt == is.stackSize ) { return true; } @@ -113,13 +113,13 @@ public final class BC extends BaseModule implements IBC @Override public boolean addItemsToPipe( TileEntity te, ItemStack is, ForgeDirection dir ) { - if ( is != null && te != null && te instanceof IInjectable ) + if( is != null && te != null && te instanceof IInjectable ) { IInjectable pt = (IInjectable) te; - if ( pt.canInjectItems( dir ) ) + if( pt.canInjectItems( dir ) ) { int amt = pt.injectItem( is, false, dir, null ); - if ( amt == is.stackSize ) + if( amt == is.stackSize ) { pt.injectItem( is, true, dir, null ); return true; @@ -133,7 +133,7 @@ public final class BC extends BaseModule implements IBC @Override public boolean isFacade( ItemStack is ) { - if ( is == null ) + if( is == null ) return false; return is.getItem() instanceof IFacadeItem; @@ -142,7 +142,7 @@ public final class BC extends BaseModule implements IBC @Override public boolean isPipe( TileEntity te, ForgeDirection dir ) { - if ( te instanceof IPipeTile ) + if( te instanceof IPipeTile ) { final IPipeTile pipeTile = (IPipeTile) te; return !pipeTile.hasPipePluggable( dir.getOpposite() ); @@ -154,7 +154,7 @@ public final class BC extends BaseModule implements IBC @Override public void addFacade( ItemStack item ) { - if ( item != null ) + if( item != null ) FMLInterModComms.sendMessage( "BuildCraft|Transport", "add-facade", item ); } @@ -214,7 +214,7 @@ public final class BC extends BaseModule implements IBC return new FacadePart( facade, side ); } - catch ( Throwable ignored ) + catch( Throwable ignored ) { } @@ -233,14 +233,14 @@ public final class BC extends BaseModule implements IBC { final Item maybeFacadeItem = facade.getItem(); - if ( maybeFacadeItem instanceof buildcraft.api.facades.IFacadeItem ) + if( maybeFacadeItem instanceof buildcraft.api.facades.IFacadeItem ) { final buildcraft.api.facades.IFacadeItem facadeItem = (buildcraft.api.facades.IFacadeItem) maybeFacadeItem; final Block[] blocks = facadeItem.getBlocksForFacade( facade ); final int[] metas = facadeItem.getMetaValuesForFacade( facade ); - if ( blocks.length > 0 && metas.length > 0 ) + if( blocks.length > 0 && metas.length > 0 ) { return new ItemStack( blocks[0], 1, metas[0] ); } @@ -256,21 +256,13 @@ public final class BC extends BaseModule implements IBC { return BuildCraftTransport.instance.pipeIconProvider.getIcon( PipeIconProvider.TYPE.PipeStructureCobblestone.ordinal() ); // Structure } - catch ( Throwable ignored ) + catch( Throwable ignored ) { } return null; // Pipe } - private void addFacadeStack( IBlockDefinition definition ) - { - for ( ItemStack facadeStack : definition.maybeStack( 1 ).asSet() ) - { - this.addFacade( facadeStack ); - } - } - @Override public void init() { @@ -290,12 +282,12 @@ public final class BC extends BaseModule implements IBC { this.initBuilderSupport(); } - catch ( Throwable builderSupport ) + catch( Throwable builderSupport ) { // not supported? } - for ( Block skyStoneBlock : blocks.skyStone().maybeBlock().asSet() ) + for( Block skyStoneBlock : blocks.skyStone().maybeBlock().asSet() ) { this.addFacade( new ItemStack( skyStoneBlock, 1, 0 ) ); this.addFacade( new ItemStack( skyStoneBlock, 1, 1 ) ); @@ -304,6 +296,14 @@ public final class BC extends BaseModule implements IBC } } + private void addFacadeStack( IBlockDefinition definition ) + { + for( ItemStack facadeStack : definition.maybeStack( 1 ).asSet() ) + { + this.addFacade( facadeStack ); + } + } + private void initBuilderSupport() { final ISchematicRegistry schematicRegistry = BuilderAPI.schematicRegistry; @@ -311,7 +311,7 @@ public final class BC extends BaseModule implements IBC final IBlocks blocks = AEApi.instance().definitions().blocks(); final IBlockDefinition maybeMultiPart = blocks.multiPart(); - for ( Method blockDefinition : blocks.getClass().getMethods() ) + for( Method blockDefinition : blocks.getClass().getMethods() ) { AEItemDefinition def; try @@ -319,20 +319,20 @@ public final class BC extends BaseModule implements IBC def = (AEItemDefinition) blockDefinition.invoke( blocks ); Block myBlock = def.block(); - if ( myBlock instanceof IOrientableBlock && ( (IOrientableBlock) myBlock ).usesMetadata() && def.entity() == null ) + if( myBlock instanceof IOrientableBlock && ( (IOrientableBlock) myBlock ).usesMetadata() && def.entity() == null ) { schematicRegistry.registerSchematicBlock( myBlock, AERotatableBlockSchematic.class ); } - else if ( maybeMultiPart.isSameAs( new ItemStack( myBlock ) ) ) + else if( maybeMultiPart.isSameAs( new ItemStack( myBlock ) ) ) { schematicRegistry.registerSchematicBlock( myBlock, AECableSchematicTile.class ); } - else if ( def.entity() != null ) + else if( def.entity() != null ) { schematicRegistry.registerSchematicBlock( myBlock, AEGenericSchematicTile.class ); } } - catch ( Throwable t ) + catch( Throwable t ) { // :P } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java b/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java index 1a431f7eb..d4e2b4bf2 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java @@ -18,6 +18,7 @@ package appeng.integration.modules.BCHelpers; + import java.util.Set; import net.minecraft.entity.player.EntityPlayer; @@ -38,11 +39,12 @@ import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; import appeng.parts.CableBusContainer; + public class AECableSchematicTile extends AEGenericSchematicTile implements IPartHost { @Override - public void rotateLeft(IBuilderContext context) + public void rotateLeft( IBuilderContext context ) { CableBusContainer cbc = new CableBusContainer( this ); cbc.readFromNBT( this.tileNBT ); @@ -60,25 +62,25 @@ public class AECableSchematicTile extends AEGenericSchematicTile implements IPar } @Override - public boolean canAddPart(ItemStack part, ForgeDirection side) + public boolean canAddPart( ItemStack part, ForgeDirection side ) { return false; } @Override - public ForgeDirection addPart(ItemStack is, ForgeDirection side, EntityPlayer owner) + public ForgeDirection addPart( ItemStack is, ForgeDirection side, EntityPlayer owner ) { return null; } @Override - public IPart getPart(ForgeDirection side) + public IPart getPart( ForgeDirection side ) { return null; } @Override - public void removePart(ForgeDirection side, boolean suppressUpdate) + public void removePart( ForgeDirection side, boolean suppressUpdate ) { } @@ -114,13 +116,13 @@ public class AECableSchematicTile extends AEGenericSchematicTile implements IPar } @Override - public boolean isBlocked(ForgeDirection side) + public boolean isBlocked( ForgeDirection side ) { return false; } @Override - public SelectedPart selectPart(Vec3 pos) + public SelectedPart selectPart( Vec3 pos ) { return null; } @@ -138,7 +140,7 @@ public class AECableSchematicTile extends AEGenericSchematicTile implements IPar } @Override - public boolean hasRedstone(ForgeDirection side) + public boolean hasRedstone( ForgeDirection side ) { return false; } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java b/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java index a023640c4..961481286 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java @@ -18,27 +18,30 @@ package appeng.integration.modules.BCHelpers; + import java.util.ArrayList; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +import buildcraft.api.blueprints.IBuilderContext; +import buildcraft.api.blueprints.SchematicTile; + import appeng.api.util.ICommonTile; import appeng.tile.AEBaseTile; import appeng.util.Platform; -import buildcraft.api.blueprints.IBuilderContext; -import buildcraft.api.blueprints.SchematicTile; + public class AEGenericSchematicTile extends SchematicTile { @Override - public void storeRequirements(IBuilderContext context, int x, int y, int z) + public void storeRequirements( IBuilderContext context, int x, int y, int z ) { TileEntity tile = context.world().getTileEntity( x, y, z ); ArrayList list = new ArrayList(); - if ( tile instanceof AEBaseTile ) + if( tile instanceof AEBaseTile ) { ICommonTile tcb = (AEBaseTile) tile; tcb.getDrops( tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, list ); @@ -48,14 +51,14 @@ public class AEGenericSchematicTile extends SchematicTile } @Override - public void rotateLeft(IBuilderContext context) + public void rotateLeft( IBuilderContext context ) { - if ( this.tileNBT.hasKey( "orientation_forward" ) && this.tileNBT.hasKey( "orientation_up" ) ) + if( this.tileNBT.hasKey( "orientation_forward" ) && this.tileNBT.hasKey( "orientation_up" ) ) { String forward = this.tileNBT.getString( "orientation_forward" ); String up = this.tileNBT.getString( "orientation_up" ); - if ( forward != null && up != null ) + if( forward != null && up != null ) { try { @@ -68,12 +71,11 @@ public class AEGenericSchematicTile extends SchematicTile this.tileNBT.setString( "orientation_forward", fdForward.name() ); this.tileNBT.setString( "orientation_up", fdUp.name() ); } - catch (Throwable ignored) + catch( Throwable ignored ) { } } } } - } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java b/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java index 4c196a0f1..2d9e4c518 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java @@ -18,6 +18,7 @@ package appeng.integration.modules.BCHelpers; + import net.minecraftforge.common.util.ForgeDirection; import buildcraft.api.blueprints.IBuilderContext; @@ -25,17 +26,17 @@ import buildcraft.api.blueprints.SchematicBlock; import appeng.util.Platform; + public class AERotatableBlockSchematic extends SchematicBlock { @Override - public void rotateLeft(IBuilderContext context) + public void rotateLeft( IBuilderContext context ) { - if ( this.meta < 6 ) + if( this.meta < 6 ) { ForgeDirection d = Platform.rotateAround( ForgeDirection.values()[this.meta], ForgeDirection.DOWN ); this.meta = d.ordinal(); } } - } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java index d9863916e..1320c1ade 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java @@ -18,6 +18,7 @@ package appeng.integration.modules.BCHelpers; + import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -27,21 +28,21 @@ import appeng.api.storage.IMEInventory; import appeng.api.storage.StorageChannel; import appeng.integration.modules.BC; + public class BCPipeHandler implements IExternalStorageHandler { @Override - public boolean canHandle(TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource mySrc) + public boolean canHandle( TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource mySrc ) { return chan == StorageChannel.ITEMS && BC.instance.isPipe( te, d ); } @Override - public IMEInventory getInventory(TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource src) + public IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource src ) { - if ( chan == StorageChannel.ITEMS ) + if( chan == StorageChannel.ITEMS ) return new BCPipeInventory( te, d ); return null; } - } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java index f9efc3387..417dd826a 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java @@ -18,6 +18,7 @@ package appeng.integration.modules.BCHelpers; + import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -29,48 +30,49 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.integration.modules.BC; + public class BCPipeInventory implements IMEInventory { final TileEntity te; final ForgeDirection dir; - public BCPipeInventory(TileEntity _te, ForgeDirection _dir) { + public BCPipeInventory( TileEntity _te, ForgeDirection _dir ) + { this.te = _te; this.dir = _dir; } + @Override + public IAEItemStack injectItems( IAEItemStack input, Actionable mode, BaseActionSource src ) + { + if( mode == Actionable.SIMULATE ) + { + if( BC.instance.canAddItemsToPipe( this.te, input.getItemStack(), this.dir ) ) + return null; + return input; + } + + if( BC.instance.addItemsToPipe( this.te, input.getItemStack(), this.dir ) ) + return null; + return input; + } + + @Override + public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) + { + return null; + } + + @Override + public IItemList getAvailableItems( IItemList out ) + { + return out; + } + @Override public StorageChannel getChannel() { return StorageChannel.ITEMS; } - - @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable mode, BaseActionSource src) - { - if ( mode == Actionable.SIMULATE ) - { - if ( BC.instance.canAddItemsToPipe( this.te, input.getItemStack(), this.dir ) ) - return null; - return input; - } - - if ( BC.instance.addItemsToPipe( this.te, input.getItemStack(), this.dir ) ) - return null; - return input; - } - - @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) - { - return null; - } - - @Override - public IItemList getAvailableItems(IItemList out) - { - return out; - } - } diff --git a/src/main/java/appeng/integration/modules/BetterStorage.java b/src/main/java/appeng/integration/modules/BetterStorage.java index 038a038e0..a908dd21b 100644 --- a/src/main/java/appeng/integration/modules/BetterStorage.java +++ b/src/main/java/appeng/integration/modules/BetterStorage.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraftforge.common.util.ForgeDirection; @@ -28,21 +29,22 @@ import appeng.integration.modules.helpers.BSCrateHandler; import appeng.integration.modules.helpers.BSCrateStorageAdaptor; import appeng.util.InventoryAdaptor; + public class BetterStorage implements IIntegrationModule, IBetterStorage { public static BetterStorage instance; @Override - public boolean isStorageCrate(Object te) + public boolean isStorageCrate( Object te ) { return te instanceof ICrateStorage; } @Override - public InventoryAdaptor getAdaptor(Object te, ForgeDirection d) + public InventoryAdaptor getAdaptor( Object te, ForgeDirection d ) { - if ( te instanceof ICrateStorage ) + if( te instanceof ICrateStorage ) { return new BSCrateStorageAdaptor( te, d ); } @@ -60,5 +62,4 @@ public class BetterStorage implements IIntegrationModule, IBetterStorage { AEApi.instance().registries().externalStorage().addExternalStorageInterface( new BSCrateHandler() ); } - } diff --git a/src/main/java/appeng/integration/modules/CLApi.java b/src/main/java/appeng/integration/modules/CLApi.java index c25b36834..88fa178fe 100644 --- a/src/main/java/appeng/integration/modules/CLApi.java +++ b/src/main/java/appeng/integration/modules/CLApi.java @@ -18,10 +18,12 @@ package appeng.integration.modules; + import appeng.api.util.AEColor; import appeng.integration.BaseModule; import appeng.integration.abstraction.ICLApi; + public class CLApi extends BaseModule implements ICLApi { @@ -40,12 +42,12 @@ public class CLApi extends BaseModule implements ICLApi } @Override - public int colorLight(AEColor color, int light) + public int colorLight( AEColor color, int light ) { int mv = color.mediumVariant; - float r = (mv >> 16) & 0xff; - float g = (mv >> 8) & 0xff; + float r = ( mv >> 16 ) & 0xff; + float g = ( mv >> 8 ) & 0xff; float b = ( mv ) & 0xff; return coloredlightscore.src.api.CLApi.makeRGBLightValue( r / 255.0f, g / 255.0f, b / 255.0f, light / 15.0f ); diff --git a/src/main/java/appeng/integration/modules/CraftGuide.java b/src/main/java/appeng/integration/modules/CraftGuide.java index c82dea5f9..c6f624a05 100644 --- a/src/main/java/appeng/integration/modules/CraftGuide.java +++ b/src/main/java/appeng/integration/modules/CraftGuide.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import java.util.Arrays; import java.util.List; @@ -51,89 +52,68 @@ import appeng.integration.IIntegrationModule; import appeng.recipes.game.ShapedRecipe; import appeng.recipes.game.ShapelessRecipe; + public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModule, RecipeProvider, StackInfoSource, RecipeGenerator { public static CraftGuide instance; - private final Slot[] shapelessCraftingSlots = new ItemSlot[] { new ItemSlot( 3, 3, 16, 16 ), new ItemSlot( 21, 3, 16, 16 ), new ItemSlot( 39, 3, 16, 16 ), - new ItemSlot( 3, 21, 16, 16 ), new ItemSlot( 21, 21, 16, 16 ), new ItemSlot( 39, 21, 16, 16 ), new ItemSlot( 3, 39, 16, 16 ), - new ItemSlot( 21, 39, 16, 16 ), new ItemSlot( 39, 39, 16, 16 ), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ), }; + private final Slot[] shapelessCraftingSlots = new ItemSlot[] { new ItemSlot( 3, 3, 16, 16 ), new ItemSlot( 21, 3, 16, 16 ), new ItemSlot( 39, 3, 16, 16 ), new ItemSlot( 3, 21, 16, 16 ), new ItemSlot( 21, 21, 16, 16 ), new ItemSlot( 39, 21, 16, 16 ), new ItemSlot( 3, 39, 16, 16 ), new ItemSlot( 21, 39, 16, 16 ), new ItemSlot( 39, 39, 16, 16 ), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ), }; - private final Slot[] craftingSlotsOwnBackground = new ItemSlot[] { new ItemSlot( 3, 3, 16, 16 ).drawOwnBackground(), - new ItemSlot( 21, 3, 16, 16 ).drawOwnBackground(), new ItemSlot( 39, 3, 16, 16 ).drawOwnBackground(), - new ItemSlot( 3, 21, 16, 16 ).drawOwnBackground(), new ItemSlot( 21, 21, 16, 16 ).drawOwnBackground(), - new ItemSlot( 39, 21, 16, 16 ).drawOwnBackground(), new ItemSlot( 3, 39, 16, 16 ).drawOwnBackground(), - new ItemSlot( 21, 39, 16, 16 ).drawOwnBackground(), new ItemSlot( 39, 39, 16, 16 ).drawOwnBackground(), - new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ).drawOwnBackground(), }; + private final Slot[] craftingSlotsOwnBackground = new ItemSlot[] { new ItemSlot( 3, 3, 16, 16 ).drawOwnBackground(), new ItemSlot( 21, 3, 16, 16 ).drawOwnBackground(), new ItemSlot( 39, 3, 16, 16 ).drawOwnBackground(), new ItemSlot( 3, 21, 16, 16 ).drawOwnBackground(), new ItemSlot( 21, 21, 16, 16 ).drawOwnBackground(), new ItemSlot( 39, 21, 16, 16 ).drawOwnBackground(), new ItemSlot( 3, 39, 16, 16 ).drawOwnBackground(), new ItemSlot( 21, 39, 16, 16 ).drawOwnBackground(), new ItemSlot( 39, 39, 16, 16 ).drawOwnBackground(), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ).drawOwnBackground(), }; - private final Slot[] smallCraftingSlotsOwnBackground = new ItemSlot[] { new ItemSlot( 12, 12, 16, 16 ).drawOwnBackground(), - new ItemSlot( 30, 12, 16, 16 ).drawOwnBackground(), new ItemSlot( 12, 30, 16, 16 ).drawOwnBackground(), - new ItemSlot( 30, 30, 16, 16 ).drawOwnBackground(), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ).drawOwnBackground(), }; + private final Slot[] smallCraftingSlotsOwnBackground = new ItemSlot[] { new ItemSlot( 12, 12, 16, 16 ).drawOwnBackground(), new ItemSlot( 30, 12, 16, 16 ).drawOwnBackground(), new ItemSlot( 12, 30, 16, 16 ).drawOwnBackground(), new ItemSlot( 30, 30, 16, 16 ).drawOwnBackground(), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ).drawOwnBackground(), }; - private final Slot[] craftingSlots = new ItemSlot[] { new ItemSlot( 3, 3, 16, 16 ), new ItemSlot( 21, 3, 16, 16 ), new ItemSlot( 39, 3, 16, 16 ), - new ItemSlot( 3, 21, 16, 16 ), new ItemSlot( 21, 21, 16, 16 ), new ItemSlot( 39, 21, 16, 16 ), new ItemSlot( 3, 39, 16, 16 ), - new ItemSlot( 21, 39, 16, 16 ), new ItemSlot( 39, 39, 16, 16 ), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ), }; + private final Slot[] craftingSlots = new ItemSlot[] { new ItemSlot( 3, 3, 16, 16 ), new ItemSlot( 21, 3, 16, 16 ), new ItemSlot( 39, 3, 16, 16 ), new ItemSlot( 3, 21, 16, 16 ), new ItemSlot( 21, 21, 16, 16 ), new ItemSlot( 39, 21, 16, 16 ), new ItemSlot( 3, 39, 16, 16 ), new ItemSlot( 21, 39, 16, 16 ), new ItemSlot( 39, 39, 16, 16 ), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ), }; - private final Slot[] smallCraftingSlots = new ItemSlot[] { new ItemSlot( 12, 12, 16, 16 ), new ItemSlot( 30, 12, 16, 16 ), new ItemSlot( 12, 30, 16, 16 ), - new ItemSlot( 30, 30, 16, 16 ), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ), }; + private final Slot[] smallCraftingSlots = new ItemSlot[] { new ItemSlot( 12, 12, 16, 16 ), new ItemSlot( 30, 12, 16, 16 ), new ItemSlot( 12, 30, 16, 16 ), new ItemSlot( 30, 30, 16, 16 ), new ItemSlot( 59, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ), }; - private final Slot[] furnaceSlots = new ItemSlot[] { new ItemSlot( 13, 21, 16, 16 ), - new ItemSlot( 50, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ), }; + private final Slot[] furnaceSlots = new ItemSlot[] { new ItemSlot( 13, 21, 16, 16 ), new ItemSlot( 50, 21, 16, 16, true ).setSlotType( SlotType.OUTPUT_SLOT ), }; + RecipeGenerator parent; @Override - public String getInfo(ItemStack itemStack) + public String getInfo( ItemStack itemStack ) { // :P return null; } - RecipeGenerator parent; - @Override - public void generateRecipes(RecipeGenerator generator) + public void generateRecipes( RecipeGenerator generator ) { this.parent = generator; RecipeTemplate craftingTemplate; RecipeTemplate smallCraftingTemplate; - if ( uristqwerty.CraftGuide.CraftGuide.newerBackgroundStyle ) + if( uristqwerty.CraftGuide.CraftGuide.newerBackgroundStyle ) { craftingTemplate = generator.createRecipeTemplate( this.craftingSlotsOwnBackground, null ); smallCraftingTemplate = generator.createRecipeTemplate( this.smallCraftingSlotsOwnBackground, null ); } else { - craftingTemplate = new DefaultRecipeTemplate( this.craftingSlots, RecipeGeneratorImplementation.workbench, new TextureClip( - DynamicTexture.instance( "recipe_backgrounds" ), 1, 1, 79, 58 ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 1, - 79, 58 ) ); + craftingTemplate = new DefaultRecipeTemplate( this.craftingSlots, RecipeGeneratorImplementation.workbench, new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 1, 79, 58 ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 1, 79, 58 ) ); - smallCraftingTemplate = new DefaultRecipeTemplate( this.smallCraftingSlots, RecipeGeneratorImplementation.workbench, new TextureClip( - DynamicTexture.instance( "recipe_backgrounds" ), 1, 61, 79, 58 ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 61, - 79, 58 ) ); + smallCraftingTemplate = new DefaultRecipeTemplate( this.smallCraftingSlots, RecipeGeneratorImplementation.workbench, new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 61, 79, 58 ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 61, 79, 58 ) ); } - RecipeTemplate shapelessTemplate = new DefaultRecipeTemplate( this.shapelessCraftingSlots, RecipeGeneratorImplementation.workbench, new TextureClip( - DynamicTexture.instance( "recipe_backgrounds" ), 1, 121, 79, 58 ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 121, - 79, 58 ) ); + RecipeTemplate shapelessTemplate = new DefaultRecipeTemplate( this.shapelessCraftingSlots, RecipeGeneratorImplementation.workbench, new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 121, 79, 58 ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 121, 79, 58 ) ); - RecipeTemplate furnaceTemplate = new DefaultRecipeTemplate( this.furnaceSlots, new ItemStack( Blocks.furnace ), new TextureClip( - DynamicTexture.instance( "recipe_backgrounds" ), 1, 181, 79, 58 ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 181, - 79, 58 ) ); + RecipeTemplate furnaceTemplate = new DefaultRecipeTemplate( this.furnaceSlots, new ItemStack( Blocks.furnace ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 181, 79, 58 ), new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 181, 79, 58 ) ); this.addCraftingRecipes( craftingTemplate, smallCraftingTemplate, shapelessTemplate, this ); this.addGrinderRecipes( furnaceTemplate, this ); this.addInscriberRecipes( furnaceTemplate, this ); } - private void addCraftingRecipes(RecipeTemplate template, RecipeTemplate templateSmall, RecipeTemplate templateShapeless, RecipeGenerator generator) + private void addCraftingRecipes( RecipeTemplate template, RecipeTemplate templateSmall, RecipeTemplate templateShapeless, RecipeGenerator generator ) { List recipes = CraftingManager.getInstance().getRecipeList(); int errCount = 0; - for (Object o : recipes) + for( Object o : recipes ) { try { @@ -141,11 +121,11 @@ public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModul Object[] items = generator.getCraftingRecipe( recipe, true ); - if ( items.length == 5 ) + if( items.length == 5 ) { generator.addRecipe( templateSmall, items ); } - else if ( recipe instanceof ShapelessRecipe ) + else if( recipe instanceof ShapelessRecipe ) { generator.addRecipe( templateShapeless, items ); } @@ -154,13 +134,11 @@ public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModul generator.addRecipe( template, items ); } } - catch (Exception e) + catch( Exception e ) { - if ( errCount >= 5 ) + if( errCount >= 5 ) { - CraftGuideLog - .log( "CraftGuide DefaultRecipeProvider: Stack trace limit reached, further stack traces from this invocation will not be logged to the console. They will still be logged to (.minecraft)/config/CraftGuide/CraftGuide.log", - true ); + CraftGuideLog.log( "CraftGuide DefaultRecipeProvider: Stack trace limit reached, further stack traces from this invocation will not be logged to the console. They will still be logged to (.minecraft)/config/CraftGuide/CraftGuide.log", true ); errCount = -1; } else @@ -174,83 +152,80 @@ public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModul } } - private void addGrinderRecipes(RecipeTemplate template, RecipeGenerator generator) + private void addGrinderRecipes( RecipeTemplate template, RecipeGenerator generator ) { } - private void addInscriberRecipes(RecipeTemplate template, RecipeGenerator generator) + private void addInscriberRecipes( RecipeTemplate template, RecipeGenerator generator ) { } @Override - public RecipeTemplate createRecipeTemplate(Slot[] slots, ItemStack craftingType) + public RecipeTemplate createRecipeTemplate( Slot[] slots, ItemStack craftingType ) { return this.parent.createRecipeTemplate( slots, craftingType ); } @Override - public RecipeTemplate createRecipeTemplate(Slot[] slots, ItemStack craftingType, String backgroundTexture, int backgroundX, int backgroundY, - int backgroundSelectedX, int backgroundSelectedY) + public RecipeTemplate createRecipeTemplate( Slot[] slots, ItemStack craftingType, String backgroundTexture, int backgroundX, int backgroundY, int backgroundSelectedX, int backgroundSelectedY ) { return this.parent.createRecipeTemplate( slots, craftingType, backgroundTexture, backgroundX, backgroundY, backgroundSelectedX, backgroundSelectedY ); } @Override - public RecipeTemplate createRecipeTemplate(Slot[] slots, ItemStack craftingType, String backgroundTexture, int backgroundX, int backgroundY, - String backgroundSelectedTexture, int backgroundSelectedX, int backgroundSelectedY) + public RecipeTemplate createRecipeTemplate( Slot[] slots, ItemStack craftingType, String backgroundTexture, int backgroundX, int backgroundY, String backgroundSelectedTexture, int backgroundSelectedX, int backgroundSelectedY ) { - return this.parent.createRecipeTemplate( slots, craftingType, backgroundTexture, backgroundX, backgroundY, backgroundSelectedTexture, backgroundSelectedX, - backgroundSelectedY ); + return this.parent.createRecipeTemplate( slots, craftingType, backgroundTexture, backgroundX, backgroundY, backgroundSelectedTexture, backgroundSelectedX, backgroundSelectedY ); } @Override - public void addRecipe(RecipeTemplate template, Object[] crafting) + public void addRecipe( RecipeTemplate template, Object[] crafting ) { this.parent.addRecipe( template, crafting ); } @Override - public void addRecipe(CraftGuideRecipe recipe, ItemStack craftingType) + public void addRecipe( CraftGuideRecipe recipe, ItemStack craftingType ) { this.parent.addRecipe( recipe, craftingType ); } @Override - public void setDefaultTypeVisibility(ItemStack type, boolean visible) + public void setDefaultTypeVisibility( ItemStack type, boolean visible ) { this.parent.setDefaultTypeVisibility( type, visible ); } @Override - public Object[] getCraftingRecipe(IRecipe recipe) + public Object[] getCraftingRecipe( IRecipe recipe ) { return this.getCraftingRecipe( recipe, true ); } - Object[] getCraftingShapelessRecipe(List items, ItemStack recipeOutput) + Object[] getCraftingShapelessRecipe( List items, ItemStack recipeOutput ) { Object[] output = new Object[10]; - for (int i = 0; i < items.size(); i++) + for( int i = 0; i < items.size(); i++ ) { output[i] = items.get( i ); - if ( output[i] instanceof ItemStack[] ) + if( output[i] instanceof ItemStack[] ) output[i] = Arrays.asList( (ItemStack[]) output[i] ); - if ( output[i] instanceof IIngredient ) + if( output[i] instanceof IIngredient ) { try { - output[i] = this.toCG( ((IIngredient) output[i]).getItemStackSet() ); + output[i] = this.toCG( ( (IIngredient) output[i] ).getItemStackSet() ); } - catch (RegistrationError ignored) + catch( RegistrationError ignored ) { } - catch (MissingIngredientError ignored) + catch( MissingIngredientError ignored ) { } @@ -261,67 +236,31 @@ public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModul return output; } - Object[] getCraftingShapedRecipe(int width, int height, Object[] items, ItemStack recipeOutput) - { - Object[] output = new Object[10]; - - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - int i = y * 3 + x; - output[i] = items[y * width + x]; - - if ( output[i] instanceof ItemStack[] ) - output[i] = Arrays.asList( (ItemStack[]) output[i] ); - - if ( output[i] instanceof IIngredient ) - { - try - { - output[i] = this.toCG( ((IIngredient) output[i]).getItemStackSet() ); - } - catch (RegistrationError ignored) - { - - } - catch (MissingIngredientError ignored) - { - - } - } - } - } - - output[9] = recipeOutput; - return output; - } - - Object[] getSmallShapedRecipe(int width, int height, Object[] items, ItemStack recipeOutput) + Object[] getSmallShapedRecipe( int width, int height, Object[] items, ItemStack recipeOutput ) { Object[] output = new Object[5]; - for (int y = 0; y < height; y++) + for( int y = 0; y < height; y++ ) { - for (int x = 0; x < width; x++) + for( int x = 0; x < width; x++ ) { int i = y * 2 + x; output[i] = items[y * width + x]; - if ( output[i] instanceof ItemStack[] ) + if( output[i] instanceof ItemStack[] ) output[i] = Arrays.asList( (ItemStack[]) output[i] ); - if ( output[i] instanceof IIngredient ) + if( output[i] instanceof IIngredient ) { try { - output[i] = this.toCG( ((IIngredient) output[i]).getItemStackSet() ); + output[i] = this.toCG( ( (IIngredient) output[i] ).getItemStackSet() ); } - catch (RegistrationError ignored) + catch( RegistrationError ignored ) { } - catch (MissingIngredientError ignored) + catch( MissingIngredientError ignored ) { } @@ -333,14 +272,50 @@ public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModul return output; } - private Object toCG(ItemStack[] itemStackSet) + Object[] getCraftingShapedRecipe( int width, int height, Object[] items, ItemStack recipeOutput ) + { + Object[] output = new Object[10]; + + for( int y = 0; y < height; y++ ) + { + for( int x = 0; x < width; x++ ) + { + int i = y * 3 + x; + output[i] = items[y * width + x]; + + if( output[i] instanceof ItemStack[] ) + output[i] = Arrays.asList( (ItemStack[]) output[i] ); + + if( output[i] instanceof IIngredient ) + { + try + { + output[i] = this.toCG( ( (IIngredient) output[i] ).getItemStackSet() ); + } + catch( RegistrationError ignored ) + { + + } + catch( MissingIngredientError ignored ) + { + + } + } + } + } + + output[9] = recipeOutput; + return output; + } + + private Object toCG( ItemStack[] itemStackSet ) { List list = Arrays.asList( itemStackSet ); - for (int x = 0; x < list.size(); x++) + for( int x = 0; x < list.size(); x++ ) { list.set( x, list.get( x ).copy() ); - if ( list.get( x ).stackSize == 0 ) + if( list.get( x ).stackSize == 0 ) list.get( x ).stackSize = 1; } @@ -348,20 +323,20 @@ public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModul } @Override - public Object[] getCraftingRecipe(IRecipe recipe, boolean allowSmallGrid) + public Object[] getCraftingRecipe( IRecipe recipe, boolean allowSmallGrid ) { - if ( recipe instanceof ShapelessRecipe ) + if( recipe instanceof ShapelessRecipe ) { List items = ReflectionHelper.getPrivateValue( ShapelessRecipe.class, (ShapelessRecipe) recipe, "input" ); return this.getCraftingShapelessRecipe( items, recipe.getRecipeOutput() ); } - else if ( recipe instanceof ShapedRecipe ) + else if( recipe instanceof ShapedRecipe ) { int width = ReflectionHelper.getPrivateValue( ShapedRecipe.class, (ShapedRecipe) recipe, "width" ); int height = ReflectionHelper.getPrivateValue( ShapedRecipe.class, (ShapedRecipe) recipe, "height" ); Object[] items = ReflectionHelper.getPrivateValue( ShapedRecipe.class, (ShapedRecipe) recipe, "input" ); - if ( allowSmallGrid && width < 3 && height < 3 ) + if( allowSmallGrid && width < 3 && height < 3 ) { return this.getSmallShapedRecipe( width, height, items, recipe.getRecipeOutput() ); } @@ -369,7 +344,6 @@ public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModul { return this.getCraftingShapedRecipe( width, height, items, recipe.getRecipeOutput() ); } - } return null; @@ -386,5 +360,4 @@ public class CraftGuide extends CraftGuideAPIObject implements IIntegrationModul { } - } diff --git a/src/main/java/appeng/integration/modules/DSU.java b/src/main/java/appeng/integration/modules/DSU.java index 2f6e45ab4..fb96ae4a3 100644 --- a/src/main/java/appeng/integration/modules/DSU.java +++ b/src/main/java/appeng/integration/modules/DSU.java @@ -58,5 +58,4 @@ public class DSU extends BaseModule implements IDSU { AEApi.instance().registries().externalStorage().addExternalStorageInterface( new MFRDSUHandler() ); } - } diff --git a/src/main/java/appeng/integration/modules/FMP.java b/src/main/java/appeng/integration/modules/FMP.java index 5fa9b1571..75a341f7f 100644 --- a/src/main/java/appeng/integration/modules/FMP.java +++ b/src/main/java/appeng/integration/modules/FMP.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import java.util.Collection; import java.util.List; @@ -53,17 +54,18 @@ import appeng.integration.abstraction.IFMP; import appeng.integration.modules.helpers.FMPPacketEvent; import appeng.parts.CableBusContainer; + public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IFMP { public static FMP instance; @Override - public TMultiPart createPart(String name, boolean client) + public TMultiPart createPart( String name, boolean client ) { - for (PartRegistry pr : PartRegistry.values()) + for( PartRegistry pr : PartRegistry.values() ) { - if ( pr.getName().equals( name ) ) + if( pr.getName().equals( name ) ) return pr.construct( 0 ); } @@ -71,13 +73,13 @@ public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IF } @Override - public TMultiPart convert(World world, BlockCoord pos) + public TMultiPart convert( World world, BlockCoord pos ) { Block blk = world.getBlock( pos.x, pos.y, pos.z ); int meta = world.getBlockMetadata( pos.x, pos.y, pos.z ); TMultiPart part = PartRegistry.getPartByBlock( blk, meta ); - if ( part instanceof CableBusPart ) + if( part instanceof CableBusPart ) { CableBusPart cbp = (CableBusPart) part; cbp.convertFromTile( world.getTileEntity( pos.x, pos.y, pos.z ) ); @@ -86,6 +88,26 @@ public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IF return part; } + @Override + public Iterable blockTypes() + { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final List blockTypes = Lists.newArrayListWithCapacity( 2 ); + + this.addBlockTypes( blockTypes, blocks.multiPart() ); + this.addBlockTypes( blockTypes, blocks.quartzTorch() ); + + return blockTypes; + } + + private void addBlockTypes( Collection blockTypes, IBlockDefinition definition ) + { + for( Block block : definition.maybeBlock().asSet() ) + { + blockTypes.add( block ); + } + } + @Override public void init() throws Throwable { @@ -102,7 +124,7 @@ public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IF PartRegistry[] reg = PartRegistry.values(); String[] data = new String[reg.length]; - for (int x = 0; x < data.length; x++) + for( int x = 0; x < data.length; x++ ) data[x] = reg[x].getName(); MultiPartRegistry.registerConverter( this ); @@ -111,9 +133,9 @@ public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IF MultipartGenerator.registerPassThroughInterface( "appeng.helpers.AEMultiTile" ); } - private void createAndRegister(IBlockDefinition definition, int i) + private void createAndRegister( IBlockDefinition definition, int i ) { - for ( Block block : definition.maybeBlock().asSet() ) + for( Block block : definition.maybeBlock().asSet() ) { BlockMicroMaterial.createAndRegister( block, i ); } @@ -126,27 +148,27 @@ public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IF } @Override - public IPartHost getOrCreateHost(TileEntity tile) + public IPartHost getOrCreateHost( TileEntity tile ) { try { BlockCoord loc = new BlockCoord( tile.xCoord, tile.yCoord, tile.zCoord ); TileMultipart mp = TileMultipart.getOrConvertTile( tile.getWorldObj(), loc ); - if ( mp != null ) + if( mp != null ) { scala.collection.Iterator i = mp.partList().iterator(); - while (i.hasNext()) + while( i.hasNext() ) { TMultiPart p = i.next(); - if ( p instanceof CableBusPart ) + if( p instanceof CableBusPart ) return (IPartHost) p; } return new FMPPlacementHelper( mp ); } } - catch (Throwable t) + catch( Throwable t ) { AELog.error( t ); } @@ -154,30 +176,30 @@ public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IF } @Override - public CableBusContainer getCableContainer(TileEntity te) + public CableBusContainer getCableContainer( TileEntity te ) { - if ( te instanceof TileMultipart ) + if( te instanceof TileMultipart ) { TileMultipart mp = (TileMultipart) te; scala.collection.Iterator i = mp.partList().iterator(); - while (i.hasNext()) + while( i.hasNext() ) { TMultiPart p = i.next(); - if ( p instanceof CableBusPart ) - return ((CableBusPart) p).cb; + if( p instanceof CableBusPart ) + return ( (CableBusPart) p ).cb; } } return null; } @Override - public void registerPassThrough(Class layerInterface) + public void registerPassThrough( Class layerInterface ) { try { MultipartGenerator.registerPassThroughInterface( layerInterface.getName() ); } - catch (Throwable t) + catch( Throwable t ) { AELog.severe( "Failed to register " + layerInterface.getName() + " with FMP, some features may not work with MultiParts." ); AELog.error( t ); @@ -185,28 +207,8 @@ public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IF } @Override - public Event newFMPPacketEvent(EntityPlayerMP sender) + public Event newFMPPacketEvent( EntityPlayerMP sender ) { return new FMPPacketEvent( sender ); } - - @Override - public Iterable blockTypes() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final List blockTypes = Lists.newArrayListWithCapacity( 2 ); - - this.addBlockTypes( blockTypes, blocks.multiPart() ); - this.addBlockTypes( blockTypes, blocks.quartzTorch() ); - - return blockTypes; - } - - private void addBlockTypes( Collection blockTypes, IBlockDefinition definition ) - { - for ( Block block : definition.maybeBlock().asSet() ) - { - blockTypes.add( block ); - } - } } diff --git a/src/main/java/appeng/integration/modules/FZ.java b/src/main/java/appeng/integration/modules/FZ.java index 3ae80106c..f470505e6 100644 --- a/src/main/java/appeng/integration/modules/FZ.java +++ b/src/main/java/appeng/integration/modules/FZ.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -33,6 +34,7 @@ import appeng.integration.modules.helpers.FactorizationBarrel; import appeng.integration.modules.helpers.FactorizationHandler; import appeng.util.Platform; + /** * 100% Hacks. */ @@ -48,118 +50,138 @@ public class FZ implements IFZ, IIntegrationModule private static Field day_item; @Override - public ItemStack barrelGetItem(TileEntity te) + public ItemStack barrelGetItem( TileEntity te ) { try { ItemStack i = null; - if ( day_BarrelClass.isInstance( te ) ) + if( day_BarrelClass.isInstance( te ) ) i = (ItemStack) day_item.get( te ); - if ( i != null ) + if( i != null ) i = Platform.cloneItemStack( i ); return i; } - catch (IllegalArgumentException ignored) + catch( IllegalArgumentException ignored ) { } - catch (IllegalAccessException ignored) + catch( IllegalAccessException ignored ) { } return null; } @Override - public int barrelGetMaxItemCount(TileEntity te) + public int barrelGetMaxItemCount( TileEntity te ) { try { - if ( day_BarrelClass.isInstance( te ) ) + if( day_BarrelClass.isInstance( te ) ) return (Integer) day_getMaxSize.invoke( te ); } - catch (IllegalAccessException ignored) + catch( IllegalAccessException ignored ) { } - catch (IllegalArgumentException ignored) + catch( IllegalArgumentException ignored ) { } - catch (InvocationTargetException ignored) + catch( InvocationTargetException ignored ) { } return 0; } @Override - public int barrelGetItemCount(TileEntity te) + public int barrelGetItemCount( TileEntity te ) { try { - if ( day_BarrelClass.isInstance( te ) ) + if( day_BarrelClass.isInstance( te ) ) return (Integer) day_getItemCount.invoke( te ); } - catch (IllegalAccessException ignored) + catch( IllegalAccessException ignored ) { } - catch (IllegalArgumentException ignored) + catch( IllegalArgumentException ignored ) { } - catch (InvocationTargetException ignored) + catch( InvocationTargetException ignored ) { } return 0; } @Override - public void setItemType(TileEntity te, ItemStack input) + public void setItemType( TileEntity te, ItemStack input ) { try { - if ( day_BarrelClass.isInstance( te ) ) + if( day_BarrelClass.isInstance( te ) ) day_item.set( te, input == null ? null : input.copy() ); } - catch (IllegalArgumentException ignored) + catch( IllegalArgumentException ignored ) { } - catch (IllegalAccessException ignored) + catch( IllegalAccessException ignored ) { } } @Override - public void barrelSetCount(TileEntity te, int max) + public void barrelSetCount( TileEntity te, int max ) { try { - if ( day_BarrelClass.isInstance( te ) ) + if( day_BarrelClass.isInstance( te ) ) day_setItemCount.invoke( te, max ); te.markDirty(); } - catch (IllegalAccessException ignored) + catch( IllegalAccessException ignored ) { } - catch (IllegalArgumentException ignored) + catch( IllegalArgumentException ignored ) { } - catch (InvocationTargetException ignored) + catch( InvocationTargetException ignored ) { } } @Override - public IMEInventory getFactorizationBarrel(TileEntity te) + public IMEInventory getFactorizationBarrel( TileEntity te ) { return new FactorizationBarrel( this, te ); } @Override - public boolean isBarrel(TileEntity te) + public boolean isBarrel( TileEntity te ) { return day_BarrelClass.isAssignableFrom( te.getClass() ); } + @Override + public void grinderRecipe( ItemStack in, ItemStack out ) + { + try + { + Class c = Class.forName( "factorization.oreprocessing.TileEntityGrinder" ); + Method m = c.getMethod( "addRecipe", Object.class, ItemStack.class, float.class ); + + float amt = out.stackSize; + out.stackSize = 1; + + m.invoke( c, in, out, amt ); + } + catch( Throwable t ) + { + // AELog.info( "" ); + // throw new RuntimeException( t ); + } + } + @Override public void init() throws Throwable { @@ -176,24 +198,4 @@ public class FZ implements IFZ, IIntegrationModule { AEApi.instance().registries().externalStorage().addExternalStorageInterface( new FactorizationHandler() ); } - - @Override - public void grinderRecipe(ItemStack in, ItemStack out) - { - try - { - Class c = Class.forName( "factorization.oreprocessing.TileEntityGrinder" ); - Method m = c.getMethod( "addRecipe", Object.class, ItemStack.class, float.class ); - - float amt = out.stackSize; - out.stackSize = 1; - - m.invoke( c, in, out, amt ); - } - catch (Throwable t) - { - // AELog.info( "" ); - // throw new RuntimeException( t ); - } - } } diff --git a/src/main/java/appeng/integration/modules/IC2.java b/src/main/java/appeng/integration/modules/IC2.java index eae7cd7d1..cfc82d8ed 100644 --- a/src/main/java/appeng/integration/modules/IC2.java +++ b/src/main/java/appeng/integration/modules/IC2.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.MinecraftForge; @@ -31,12 +32,14 @@ import appeng.api.features.IP2PTunnelRegistry; import appeng.integration.BaseModule; import appeng.integration.abstraction.IIC2; + public class IC2 extends BaseModule implements IIC2 { public static IC2 instance; - public IC2() { + public IC2() + { this.testClassExistence( IEnergyTile.class ); } @@ -66,27 +69,26 @@ public class IC2 extends BaseModule implements IIC2 } @Override - public void maceratorRecipe(ItemStack in, ItemStack out) - { - ic2.api.recipe.Recipes.macerator.addRecipe( new RecipeInputItemStack( in, in.stackSize ), null, out ); - } - - @Override - public void addToEnergyNet(TileEntity appEngTile) + public void addToEnergyNet( TileEntity appEngTile ) { MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergyTile) appEngTile ) ); } @Override - public void removeFromEnergyNet(TileEntity appEngTile) + public void removeFromEnergyNet( TileEntity appEngTile ) { MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergyTile) appEngTile ) ); } @Override - public ItemStack getItem(String name) + public ItemStack getItem( String name ) { return ic2.api.item.IC2Items.getItem( name ); } + @Override + public void maceratorRecipe( ItemStack in, ItemStack out ) + { + ic2.api.recipe.Recipes.macerator.addRecipe( new RecipeInputItemStack( in, in.stackSize ), null, out ); + } } diff --git a/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java b/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java index 67ce8bb1e..d1c8b6fd8 100644 --- a/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java +++ b/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java @@ -62,11 +62,10 @@ public class ImmibisMicroblocks extends BaseModule implements IImmibisMicroblock try { this.MicroblockAPIUtils = Class.forName( "mods.immibis.microblocks.api.MicroblockAPIUtils" ); - this.mergeIntoMicroblockContainer = this.MicroblockAPIUtils.getMethod( "mergeIntoMicroblockContainer", ItemStack.class, EntityPlayer.class, World.class, - int.class, int.class, int.class, int.class, Block.class, int.class ); + this.mergeIntoMicroblockContainer = this.MicroblockAPIUtils.getMethod( "mergeIntoMicroblockContainer", ItemStack.class, EntityPlayer.class, World.class, int.class, int.class, int.class, int.class, Block.class, int.class ); this.canConvertTiles = true; } - catch ( Throwable t ) + catch( Throwable t ) { AELog.error( t ); } @@ -78,22 +77,6 @@ public class ImmibisMicroblocks extends BaseModule implements IImmibisMicroblock } - @Override - public boolean leaveParts( TileEntity te ) - { - if ( te instanceof IMultipartTile ) - { - ICoverSystem ci = ( ( IMultipartTile ) te ).getCoverSystem(); - if ( ci != null ) - { - ci.convertToContainerBlock(); - } - - return true; - } - return false; - } - @Override public IPartHost getOrCreateHost( EntityPlayer player, int side, TileEntity te ) { @@ -103,7 +86,7 @@ public class ImmibisMicroblocks extends BaseModule implements IImmibisMicroblock final int z = te.zCoord; final boolean isPartItem = player != null && player.getHeldItem() != null && player.getHeldItem().getItem() instanceof IPartItem; - if ( te instanceof IMultipartTile && this.canConvertTiles && isPartItem ) + if( te instanceof IMultipartTile && this.canConvertTiles && isPartItem ) { final IBlockDefinition multiPart = AEApi.instance().definitions().blocks().multiPart(); final Optional maybeMultiPartBlock = multiPart.maybeBlock(); @@ -111,7 +94,7 @@ public class ImmibisMicroblocks extends BaseModule implements IImmibisMicroblock final boolean multiPartPresent = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent(); - if ( multiPartPresent ) + if( multiPartPresent ) { final Block multiPartBlock = maybeMultiPartBlock.get(); final ItemStack multiPartStack = maybeMultiPartStack.get(); @@ -122,7 +105,7 @@ public class ImmibisMicroblocks extends BaseModule implements IImmibisMicroblock // int.class, int.class, int.class, int.class, Block.class, int.class ); this.mergeIntoMicroblockContainer.invoke( null, multiPartStack, player, w, x, y, z, side, multiPartBlock, 0 ); } - catch ( Throwable e ) + catch( Throwable e ) { this.canConvertTiles = false; return null; @@ -131,9 +114,25 @@ public class ImmibisMicroblocks extends BaseModule implements IImmibisMicroblock } final TileEntity tx = w.getTileEntity( x, y, z ); - if ( tx instanceof IPartHost ) - return ( IPartHost ) tx; + if( tx instanceof IPartHost ) + return (IPartHost) tx; return null; } + + @Override + public boolean leaveParts( TileEntity te ) + { + if( te instanceof IMultipartTile ) + { + ICoverSystem ci = ( (IMultipartTile) te ).getCoverSystem(); + if( ci != null ) + { + ci.convertToContainerBlock(); + } + + return true; + } + return false; + } } diff --git a/src/main/java/appeng/integration/modules/InvTweaks.java b/src/main/java/appeng/integration/modules/InvTweaks.java index 6d57932fb..6aaa7440e 100644 --- a/src/main/java/appeng/integration/modules/InvTweaks.java +++ b/src/main/java/appeng/integration/modules/InvTweaks.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import net.minecraft.item.ItemStack; import cpw.mods.fml.common.Loader; @@ -27,6 +28,7 @@ import invtweaks.api.InvTweaksAPI; import appeng.integration.BaseModule; import appeng.integration.abstraction.IInvTweaks; + public class InvTweaks extends BaseModule implements IInvTweaks { @@ -43,12 +45,12 @@ public class InvTweaks extends BaseModule implements IInvTweaks @Override public void postInit() { - if ( api == null ) + if( api == null ) throw new RuntimeException( "InvTweaks API Instance Failed." ); } @Override - public int compareItems(ItemStack i, ItemStack j) + public int compareItems( ItemStack i, ItemStack j ) { return api.compareItems( i, j ); } diff --git a/src/main/java/appeng/integration/modules/MFR.java b/src/main/java/appeng/integration/modules/MFR.java index c6a5cedea..0d9a2f58c 100644 --- a/src/main/java/appeng/integration/modules/MFR.java +++ b/src/main/java/appeng/integration/modules/MFR.java @@ -18,16 +18,19 @@ package appeng.integration.modules; + import powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection; import appeng.integration.BaseModule; + public class MFR extends BaseModule { public static MFR instance; - public MFR() { + public MFR() + { this.testClassExistence( IRedNetConnection.class ); } @@ -42,5 +45,4 @@ public class MFR extends BaseModule { } - } diff --git a/src/main/java/appeng/integration/modules/Mekanism.java b/src/main/java/appeng/integration/modules/Mekanism.java index 9c751f125..3e27ad064 100644 --- a/src/main/java/appeng/integration/modules/Mekanism.java +++ b/src/main/java/appeng/integration/modules/Mekanism.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -26,6 +27,7 @@ import cpw.mods.fml.common.event.FMLInterModComms; import appeng.integration.BaseModule; import appeng.integration.abstraction.IMekanism; + public final class Mekanism extends BaseModule implements IMekanism { @@ -44,7 +46,7 @@ public final class Mekanism extends BaseModule implements IMekanism } @Override - public void addCrusherRecipe(ItemStack in, ItemStack out) + public void addCrusherRecipe( ItemStack in, ItemStack out ) { final NBTTagCompound sendTag = this.convertToSimpleRecipe( in, out ); @@ -52,7 +54,7 @@ public final class Mekanism extends BaseModule implements IMekanism } @Override - public void addEnrichmentChamberRecipe(ItemStack in, ItemStack out) + public void addEnrichmentChamberRecipe( ItemStack in, ItemStack out ) { final NBTTagCompound sendTag = this.convertToSimpleRecipe( in, out ); diff --git a/src/main/java/appeng/integration/modules/NEI.java b/src/main/java/appeng/integration/modules/NEI.java index 8c9b3d232..6679f0c3e 100644 --- a/src/main/java/appeng/integration/modules/NEI.java +++ b/src/main/java/appeng/integration/modules/NEI.java @@ -51,6 +51,7 @@ import appeng.integration.modules.NEIHelpers.NEIInscriberRecipeHandler; import appeng.integration.modules.NEIHelpers.NEIWorldCraftingHandler; import appeng.integration.modules.NEIHelpers.TerminalCraftingSlotFinder; + public class NEI extends BaseModule implements INEI, IContainerTooltipHandler { @@ -62,19 +63,14 @@ public class NEI extends BaseModule implements INEI, IContainerTooltipHandler Method registerRecipeHandler; Method registerUsageHandler; - public NEI() throws ClassNotFoundException { + public NEI() throws ClassNotFoundException + { this.testClassExistence( GuiContainerManager.class ); this.testClassExistence( codechicken.nei.recipe.ICraftingHandler.class ); this.testClassExistence( codechicken.nei.recipe.IUsageHandler.class ); this.API = Class.forName( "codechicken.nei.api.API" ); } - public void registerRecipeHandler(Object o) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException - { - this.registerRecipeHandler.invoke( this.API, o ); - this.registerUsageHandler.invoke( this.API, o ); - } - @Override public void init() throws Throwable { @@ -87,7 +83,7 @@ public class NEI extends BaseModule implements INEI, IContainerTooltipHandler this.registerRecipeHandler( new NEIWorldCraftingHandler() ); this.registerRecipeHandler( new NEIGrinderRecipeHandler() ); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.Facades ) && AEConfig.instance.isFeatureEnabled( AEFeature.enableFacadeCrafting ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.Facades ) && AEConfig.instance.isFeatureEnabled( AEFeature.enableFacadeCrafting ) ) this.registerRecipeHandler( new NEIFacadeRecipeHandler() ); // large stack tooltips @@ -107,6 +103,12 @@ public class NEI extends BaseModule implements INEI, IContainerTooltipHandler registerGuiOverlayHandler.invoke( this.API, GuiPatternTerm.class, DefaultOverlayHandlerConstructor.newInstance( 6, 75 ), "crafting" ); } + public void registerRecipeHandler( Object o ) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException + { + this.registerRecipeHandler.invoke( this.API, o ); + this.registerUsageHandler.invoke( this.API, o ); + } + @Override public void postInit() { @@ -114,14 +116,14 @@ public class NEI extends BaseModule implements INEI, IContainerTooltipHandler } @Override - public void drawSlot(Slot s) + public void drawSlot( Slot s ) { - if ( s == null ) + if( s == null ) return; ItemStack stack = s.getStack(); - if ( stack == null ) + if( stack == null ) return; Minecraft mc = Minecraft.getMinecraft(); @@ -134,7 +136,7 @@ public class NEI extends BaseModule implements INEI, IContainerTooltipHandler } @Override - public RenderItem setItemRender(RenderItem renderItem) + public RenderItem setItemRender( RenderItem renderItem ) { try { @@ -142,31 +144,30 @@ public class NEI extends BaseModule implements INEI, IContainerTooltipHandler GuiContainerManager.drawItems = renderItem; return ri; } - catch (Throwable t) + catch( Throwable t ) { throw new RuntimeException( "Invalid version of NEI, please update", t ); } } @Override - public List handleItemDisplayName(GuiContainer arg0, ItemStack arg1, List current) + public List handleTooltip( GuiContainer arg0, int arg1, int arg2, List current ) { return current; } @Override - public List handleItemTooltip(GuiContainer guiScreen, ItemStack stack, int mouseX, int mouseY, List currentToolTip) + public List handleItemDisplayName( GuiContainer arg0, ItemStack arg1, List current ) { - if ( guiScreen instanceof AEBaseMEGui ) - return ((AEBaseMEGui) guiScreen).handleItemTooltip( stack, mouseX, mouseY, currentToolTip ); + return current; + } + + @Override + public List handleItemTooltip( GuiContainer guiScreen, ItemStack stack, int mouseX, int mouseY, List currentToolTip ) + { + if( guiScreen instanceof AEBaseMEGui ) + return ( (AEBaseMEGui) guiScreen ).handleItemTooltip( stack, mouseX, mouseY, currentToolTip ); return currentToolTip; } - - @Override - public List handleTooltip(GuiContainer arg0, int arg1, int arg2, List current) - { - return current; - } - } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java index 825670098..808a4b222 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java @@ -18,7 +18,8 @@ package appeng.integration.modules.NEIHelpers; -import java.awt.Rectangle; + +import java.awt.*; import java.util.ArrayList; import java.util.List; @@ -46,6 +47,7 @@ import appeng.core.AEConfig; import appeng.recipes.game.ShapedRecipe; import appeng.util.Platform; + public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler { @@ -56,28 +58,16 @@ public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler } @Override - public Class getGuiClass() + public void loadCraftingRecipes( String outputId, Object... results ) { - return GuiCrafting.class; - } - - @Override - public String getRecipeName() - { - return NEIClientUtils.translate( "recipe.shaped" ); - } - - @Override - public void loadCraftingRecipes(String outputId, Object... results) - { - if ( (outputId.equals( "crafting" )) && (this.getClass() == NEIAEShapedRecipeHandler.class) ) + if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIAEShapedRecipeHandler.class ) ) { List recipes = CraftingManager.getInstance().getRecipeList(); - for (IRecipe recipe : recipes) + for( IRecipe recipe : recipes ) { - if ( (recipe instanceof ShapedRecipe) ) + if( ( recipe instanceof ShapedRecipe ) ) { - if ( ((ShapedRecipe) recipe).isEnabled() ) + if( ( (ShapedRecipe) recipe ).isEnabled() ) { CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); cachedRecipe.computeVisuals(); @@ -93,14 +83,14 @@ public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler } @Override - public void loadCraftingRecipes(ItemStack result) + public void loadCraftingRecipes( ItemStack result ) { List recipes = CraftingManager.getInstance().getRecipeList(); - for (IRecipe recipe : recipes) + for( IRecipe recipe : recipes ) { - if ( (recipe instanceof ShapedRecipe) ) + if( ( recipe instanceof ShapedRecipe ) ) { - if ( ((ShapedRecipe) recipe).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) + if( ( (ShapedRecipe) recipe ).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) { CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); cachedRecipe.computeVisuals(); @@ -111,19 +101,19 @@ public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler } @Override - public void loadUsageRecipes(ItemStack ingredient) + public void loadUsageRecipes( ItemStack ingredient ) { List recipes = CraftingManager.getInstance().getRecipeList(); - for (IRecipe recipe : recipes) + for( IRecipe recipe : recipes ) { - if ( (recipe instanceof ShapedRecipe) ) + if( ( recipe instanceof ShapedRecipe ) ) { CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); - if ( ((ShapedRecipe) recipe).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) + if( ( (ShapedRecipe) recipe ).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) { cachedRecipe.computeVisuals(); - if ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) + if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) { cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); this.arecipes.add( cachedRecipe ); @@ -146,67 +136,80 @@ public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler } @Override - public boolean hasOverlay(GuiContainer gui, Container container, int recipe) + public Class getGuiClass() { - return (super.hasOverlay( gui, container, recipe )) || ((this.isRecipe2x2( recipe )) && (RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ))); + return GuiCrafting.class; } @Override - public IRecipeOverlayRenderer getOverlayRenderer(GuiContainer gui, int recipe) + public boolean hasOverlay( GuiContainer gui, Container container, int recipe ) + { + return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer( GuiContainer gui, int recipe ) { IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if ( renderer != null ) + if( renderer != null ) return renderer; IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if ( positioner == null ) + if( positioner == null ) return null; return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); } @Override - public IOverlayHandler getOverlayHandler(GuiContainer gui, int recipe) + public IOverlayHandler getOverlayHandler( GuiContainer gui, int recipe ) { IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if ( handler != null ) + if( handler != null ) return handler; return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); } - public boolean isRecipe2x2(int recipe) + public boolean isRecipe2x2( int recipe ) { - for (PositionedStack stack : this.getIngredientStacks( recipe )) + for( PositionedStack stack : this.getIngredientStacks( recipe ) ) { - if ( (stack.relx > 43) || (stack.rely > 24) ) + if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) return false; } return true; } + @Override + public String getRecipeName() + { + return NEIClientUtils.translate( "recipe.shaped" ); + } + public class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe { public final ArrayList ingredients; public final PositionedStack result; - public CachedShapedRecipe(ShapedRecipe recipe) { + public CachedShapedRecipe( ShapedRecipe recipe ) + { this.result = new PositionedStack( recipe.getRecipeOutput(), 119, 24 ); this.ingredients = new ArrayList(); this.setIngredients( recipe.getWidth(), recipe.getHeight(), recipe.getIngredients() ); } - public void setIngredients(int width, int height, Object[] items) + public void setIngredients( int width, int height, Object[] items ) { boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); - for (int x = 0; x < width; x++) + for( int x = 0; x < width; x++ ) { - for (int y = 0; y < height; y++) + for( int y = 0; y < height; y++ ) { - if ( items[(y * width + x)] != null ) + if( items[( y * width + x )] != null ) { - IIngredient ing = (IIngredient) items[(y * width + x)]; + IIngredient ing = (IIngredient) items[( y * width + x )]; try { @@ -215,35 +218,34 @@ public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler stack.setMaxSize( 1 ); this.ingredients.add( stack ); } - catch (RegistrationError ignored) + catch( RegistrationError ignored ) { } - catch (MissingIngredientError ignored) + catch( MissingIngredientError ignored ) { } - } } } } - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIAEShapedRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - @Override public PositionedStack getResult() { return this.result; } + @Override + public List getIngredients() + { + return this.getCycledIngredients( NEIAEShapedRecipeHandler.this.cycleticks / 20, this.ingredients ); + } + public void computeVisuals() { - for (PositionedStack p : this.ingredients) + for( PositionedStack p : this.ingredients ) { p.generatePermutations(); } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java index 04f5ea14d..f9ab59799 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java @@ -18,7 +18,8 @@ package appeng.integration.modules.NEIHelpers; -import java.awt.Rectangle; + +import java.awt.*; import java.util.ArrayList; import java.util.List; @@ -46,6 +47,7 @@ import appeng.core.AEConfig; import appeng.recipes.game.ShapelessRecipe; import appeng.util.Platform; + public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler { @@ -56,28 +58,16 @@ public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler } @Override - public Class getGuiClass() + public void loadCraftingRecipes( String outputId, Object... results ) { - return GuiCrafting.class; - } - - @Override - public String getRecipeName() - { - return NEIClientUtils.translate( "recipe.shapeless" ); - } - - @Override - public void loadCraftingRecipes(String outputId, Object... results) - { - if ( (outputId.equals( "crafting" )) && (this.getClass() == NEIAEShapelessRecipeHandler.class) ) + if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIAEShapelessRecipeHandler.class ) ) { List recipes = CraftingManager.getInstance().getRecipeList(); - for (IRecipe recipe : recipes) + for( IRecipe recipe : recipes ) { - if ( (recipe instanceof ShapelessRecipe) ) + if( ( recipe instanceof ShapelessRecipe ) ) { - if ( ((ShapelessRecipe) recipe).isEnabled() ) + if( ( (ShapelessRecipe) recipe ).isEnabled() ) { CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); cachedRecipe.computeVisuals(); @@ -93,14 +83,14 @@ public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler } @Override - public void loadCraftingRecipes(ItemStack result) + public void loadCraftingRecipes( ItemStack result ) { List recipes = CraftingManager.getInstance().getRecipeList(); - for (IRecipe recipe : recipes) + for( IRecipe recipe : recipes ) { - if ( (recipe instanceof ShapelessRecipe) ) + if( ( recipe instanceof ShapelessRecipe ) ) { - if ( ((ShapelessRecipe) recipe).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) + if( ( (ShapelessRecipe) recipe ).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) { CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); cachedRecipe.computeVisuals(); @@ -111,19 +101,19 @@ public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler } @Override - public void loadUsageRecipes(ItemStack ingredient) + public void loadUsageRecipes( ItemStack ingredient ) { List recipes = CraftingManager.getInstance().getRecipeList(); - for (IRecipe recipe : recipes) + for( IRecipe recipe : recipes ) { - if ( (recipe instanceof ShapelessRecipe) ) + if( ( recipe instanceof ShapelessRecipe ) ) { CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); - if ( ((ShapelessRecipe) recipe).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) + if( ( (ShapelessRecipe) recipe ).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) { cachedRecipe.computeVisuals(); - if ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) + if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) { cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); this.arecipes.add( cachedRecipe ); @@ -146,105 +136,116 @@ public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler } @Override - public boolean hasOverlay(GuiContainer gui, Container container, int recipe) + public Class getGuiClass() { - return (super.hasOverlay( gui, container, recipe )) || ((this.isRecipe2x2( recipe )) && (RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ))); + return GuiCrafting.class; } @Override - public IRecipeOverlayRenderer getOverlayRenderer(GuiContainer gui, int recipe) + public boolean hasOverlay( GuiContainer gui, Container container, int recipe ) + { + return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer( GuiContainer gui, int recipe ) { IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if ( renderer != null ) + if( renderer != null ) return renderer; IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if ( positioner == null ) + if( positioner == null ) return null; return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); } @Override - public IOverlayHandler getOverlayHandler(GuiContainer gui, int recipe) + public IOverlayHandler getOverlayHandler( GuiContainer gui, int recipe ) { IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if ( handler != null ) + if( handler != null ) return handler; return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); } - public boolean isRecipe2x2(int recipe) + public boolean isRecipe2x2( int recipe ) { - for (PositionedStack stack : this.getIngredientStacks( recipe )) + for( PositionedStack stack : this.getIngredientStacks( recipe ) ) { - if ( (stack.relx > 43) || (stack.rely > 24) ) + if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) return false; } return true; } + @Override + public String getRecipeName() + { + return NEIClientUtils.translate( "recipe.shapeless" ); + } + public class CachedShapelessRecipe extends TemplateRecipeHandler.CachedRecipe { public final ArrayList ingredients; public final PositionedStack result; - public CachedShapelessRecipe(ShapelessRecipe recipe) { + public CachedShapelessRecipe( ShapelessRecipe recipe ) + { this.result = new PositionedStack( recipe.getRecipeOutput(), 119, 24 ); this.ingredients = new ArrayList(); this.setIngredients( recipe.getInput().toArray() ); } - public void setIngredients(Object[] items) - { - boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); - for (int x = 0; x < 3; x++) - { - for (int y = 0; y < 3; y++) - { - if ( items.length > (y * 3 + x) ) - { - IIngredient ing = (IIngredient) items[(y * 3 + x)]; - - try - { - ItemStack[] is = ing.getItemStackSet(); - PositionedStack stack = new PositionedStack( useSingleItems ? Platform.findPreferred( is ) : ing.getItemStackSet(), 25 + x * 18, - 6 + y * 18, false ); - stack.setMaxSize( 1 ); - this.ingredients.add( stack ); - } - catch (RegistrationError ignored) - { - - } - catch (MissingIngredientError ignored) - { - - } - - } - } - } - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIAEShapelessRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - @Override public PositionedStack getResult() { return this.result; } + @Override + public List getIngredients() + { + return this.getCycledIngredients( NEIAEShapelessRecipeHandler.this.cycleticks / 20, this.ingredients ); + } + + public void setIngredients( Object[] items ) + { + boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); + for( int x = 0; x < 3; x++ ) + { + for( int y = 0; y < 3; y++ ) + { + if( items.length > ( y * 3 + x ) ) + { + IIngredient ing = (IIngredient) items[( y * 3 + x )]; + + try + { + ItemStack[] is = ing.getItemStackSet(); + PositionedStack stack = new PositionedStack( useSingleItems ? Platform.findPreferred( is ) : ing.getItemStackSet(), 25 + x * 18, 6 + y * 18, false ); + stack.setMaxSize( 1 ); + this.ingredients.add( stack ); + } + catch( RegistrationError ignored ) + { + + } + catch( MissingIngredientError ignored ) + { + + } + } + } + } + } + public void computeVisuals() { - for (PositionedStack p : this.ingredients) + for( PositionedStack p : this.ingredients ) p.generatePermutations(); this.result.generatePermutations(); diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java index 060aaf021..6d7f35627 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java @@ -18,6 +18,7 @@ package appeng.integration.modules.NEIHelpers; + import java.util.LinkedList; import java.util.List; @@ -39,61 +40,62 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketNEIRecipe; import appeng.util.Platform; + public class NEICraftingHandler implements IOverlayHandler { - public NEICraftingHandler(int x, int y) + final int offsetX; + final int offsetY; + + public NEICraftingHandler( int x, int y ) { this.offsetX = x; this.offsetY = y; } - final int offsetX; - final int offsetY; - @Override - public void overlayRecipe(GuiContainer gui, IRecipeHandler recipe, int recipeIndex, boolean shift) + public void overlayRecipe( GuiContainer gui, IRecipeHandler recipe, int recipeIndex, boolean shift ) { try { List ingredients = recipe.getIngredientStacks( recipeIndex ); this.overlayRecipe( gui, ingredients, shift ); } - catch (Exception ignored) + catch( Exception ignored ) { } - catch (Error ignored) + catch( Error ignored ) { } } - public void overlayRecipe(GuiContainer gui, List ingredients, boolean shift) + public void overlayRecipe( GuiContainer gui, List ingredients, boolean shift ) { try { NBTTagCompound recipe = new NBTTagCompound(); - if ( gui instanceof GuiCraftingTerm || gui instanceof GuiPatternTerm ) + if( gui instanceof GuiCraftingTerm || gui instanceof GuiPatternTerm ) { - for (PositionedStack positionedStack : ingredients) + for( PositionedStack positionedStack : ingredients ) { - int col = (positionedStack.relx - 25) / 18; - int row = (positionedStack.rely - 6) / 18; - if ( positionedStack.items != null && positionedStack.items.length > 0 ) + int col = ( positionedStack.relx - 25 ) / 18; + int row = ( positionedStack.rely - 6 ) / 18; + if( positionedStack.items != null && positionedStack.items.length > 0 ) { - for (Slot slot : (List) gui.inventorySlots.inventorySlots) + for( Slot slot : (List) gui.inventorySlots.inventorySlots ) { - if ( slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix ) + if( slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix ) { - if ( slot.getSlotIndex() == col + row * 3 ) + if( slot.getSlotIndex() == col + row * 3 ) { NBTTagList tags = new NBTTagList(); List list = new LinkedList(); // prefer pure crystals. - for (int x = 0; x < positionedStack.items.length; x++) + for( int x = 0; x < positionedStack.items.length; x++ ) { - if ( Platform.isRecipePrioritized( positionedStack.items[x] ) ) + if( Platform.isRecipePrioritized( positionedStack.items[x] ) ) { list.add( 0, positionedStack.items[x] ); } @@ -103,7 +105,7 @@ public class NEICraftingHandler implements IOverlayHandler } } - for (ItemStack is : list) + for( ItemStack is : list ) { NBTTagCompound tag = new NBTTagCompound(); is.writeToNBT( tag ); @@ -121,10 +123,10 @@ public class NEICraftingHandler implements IOverlayHandler NetworkHandler.instance.sendToServer( new PacketNEIRecipe( recipe ) ); } } - catch (Exception ignored) + catch( Exception ignored ) { } - catch (Error ignored) + catch( Error ignored ) { } } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java index 7f32f7d4b..53b018e49 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java @@ -66,12 +66,12 @@ public class NEIFacadeRecipeHandler extends TemplateRecipeHandler @Override public void loadCraftingRecipes( String outputId, Object... results ) { - if ( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIFacadeRecipeHandler.class ) ) + if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIFacadeRecipeHandler.class ) ) { final List facades = this.facade.getFacades(); - for ( ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) + for( ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) { - for ( ItemStack is : facades ) + for( ItemStack is : facades ) { CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, is ); recipe.computeVisuals(); @@ -88,9 +88,9 @@ public class NEIFacadeRecipeHandler extends TemplateRecipeHandler @Override public void loadCraftingRecipes( ItemStack result ) { - if ( result.getItem() == this.facade ) + if( result.getItem() == this.facade ) { - for ( ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) + for( ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) { CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, result ); recipe.computeVisuals(); @@ -103,16 +103,16 @@ public class NEIFacadeRecipeHandler extends TemplateRecipeHandler public void loadUsageRecipes( ItemStack ingredient ) { List facades = this.facade.getFacades(); - for ( ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) + for( ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) { - for ( ItemStack is : facades ) + for( ItemStack is : facades ) { CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, is ); - if ( recipe.contains( recipe.ingredients, ingredient.getItem() ) ) + if( recipe.contains( recipe.ingredients, ingredient.getItem() ) ) { recipe.computeVisuals(); - if ( recipe.contains( recipe.ingredients, ingredient ) ) + if( recipe.contains( recipe.ingredients, ingredient ) ) { recipe.setIngredientPermutation( recipe.ingredients, ingredient ); this.arecipes.add( recipe ); @@ -150,11 +150,11 @@ public class NEIFacadeRecipeHandler extends TemplateRecipeHandler public IRecipeOverlayRenderer getOverlayRenderer( GuiContainer gui, int recipe ) { IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if ( renderer != null ) + if( renderer != null ) return renderer; IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if ( positioner == null ) + if( positioner == null ) return null; return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); @@ -164,7 +164,7 @@ public class NEIFacadeRecipeHandler extends TemplateRecipeHandler public IOverlayHandler getOverlayHandler( GuiContainer gui, int recipe ) { IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if ( handler != null ) + if( handler != null ) return handler; return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); @@ -172,9 +172,9 @@ public class NEIFacadeRecipeHandler extends TemplateRecipeHandler public boolean isRecipe2x2( int recipe ) { - for ( PositionedStack stack : this.getIngredientStacks( recipe ) ) + for( PositionedStack stack : this.getIngredientStacks( recipe ) ) { - if ( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) + if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) return false; } return true; @@ -202,11 +202,11 @@ public class NEIFacadeRecipeHandler extends TemplateRecipeHandler public void setIngredients( int width, int height, Object[] items ) { - for ( int x = 0; x < width; x++ ) + for( int x = 0; x < width; x++ ) { - for ( int y = 0; y < height; y++ ) + for( int y = 0; y < height; y++ ) { - if ( items[( y * width + x )] != null ) + if( items[( y * width + x )] != null ) { ItemStack is = (ItemStack) items[( y * width + x )]; PositionedStack stack = new PositionedStack( is, 25 + x * 18, 6 + y * 18, false ); @@ -231,7 +231,7 @@ public class NEIFacadeRecipeHandler extends TemplateRecipeHandler public void computeVisuals() { - for ( PositionedStack p : this.ingredients ) + for( PositionedStack p : this.ingredients ) { p.generatePermutations(); } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java index dc9403aec..b5e2727fa 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java @@ -18,10 +18,8 @@ package appeng.integration.modules.NEIHelpers; -import static codechicken.lib.gui.GuiDraw.changeTexture; -import static codechicken.lib.gui.GuiDraw.drawTexturedModalRect; -import java.awt.Rectangle; +import java.awt.*; import java.util.ArrayList; import java.util.List; @@ -45,43 +43,13 @@ import appeng.api.features.IGrinderEntry; import appeng.client.gui.implementations.GuiGrinder; import appeng.core.localization.GuiText; +import static codechicken.lib.gui.GuiDraw.changeTexture; +import static codechicken.lib.gui.GuiDraw.drawTexturedModalRect; + + public class NEIGrinderRecipeHandler extends TemplateRecipeHandler { - @Override - public void drawBackground(int recipe) - { - GL11.glColor4f( 1, 1, 1, 1 ); - changeTexture( this.getGuiTexture() ); - drawTexturedModalRect( 40, 10, 75, 16 + 10, 90, 66 ); - } - - @Override - public void drawForeground(int recipe) - { - super.drawForeground( recipe ); - if ( this.arecipes.size() > recipe ) - { - CachedRecipe cr = this.arecipes.get( recipe ); - if ( cr instanceof CachedGrindStoneRecipe ) - { - CachedGrindStoneRecipe cachedRecipe = (CachedGrindStoneRecipe) cr; - if ( cachedRecipe.hasOptional ) - { - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - int width = fr.getStringWidth( cachedRecipe.Chance ); - fr.drawString( cachedRecipe.Chance, (168 - width) / 2, 5, 0 ); - } - else - { - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - int width = fr.getStringWidth( GuiText.NoSecondOutput.getLocal() ); - fr.drawString( GuiText.NoSecondOutput.getLocal(), (168 - width) / 2, 5, 0 ); - } - } - } - } - @Override public void loadTransferRects() { @@ -89,23 +57,11 @@ public class NEIGrinderRecipeHandler extends TemplateRecipeHandler } @Override - public Class getGuiClass() + public void loadCraftingRecipes( String outputId, Object... results ) { - return GuiGrinder.class; - } - - @Override - public String getRecipeName() - { - return GuiText.GrindStone.getLocal(); - } - - @Override - public void loadCraftingRecipes(String outputId, Object... results) - { - if ( (outputId.equals( "grindstone" )) && (this.getClass() == NEIGrinderRecipeHandler.class) ) + if( ( outputId.equals( "grindstone" ) ) && ( this.getClass() == NEIGrinderRecipeHandler.class ) ) { - for (IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes()) + for( IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) { CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); cachedRecipe.computeVisuals(); @@ -119,11 +75,11 @@ public class NEIGrinderRecipeHandler extends TemplateRecipeHandler } @Override - public void loadCraftingRecipes(ItemStack result) + public void loadCraftingRecipes( ItemStack result ) { - for (IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes()) + for( IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) { - if ( NEIServerUtils.areStacksSameTypeCrafting( recipe.getOutput(), result ) ) + if( NEIServerUtils.areStacksSameTypeCrafting( recipe.getOutput(), result ) ) { CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); cachedRecipe.computeVisuals(); @@ -133,16 +89,16 @@ public class NEIGrinderRecipeHandler extends TemplateRecipeHandler } @Override - public void loadUsageRecipes(ItemStack ingredient) + public void loadUsageRecipes( ItemStack ingredient ) { - for (IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes()) + for( IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) { CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); - if ( (cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() )) ) + if( ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) ) { cachedRecipe.computeVisuals(); - if ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) + if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) { cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); this.arecipes.add( cachedRecipe ); @@ -165,62 +121,108 @@ public class NEIGrinderRecipeHandler extends TemplateRecipeHandler } @Override - public boolean hasOverlay(GuiContainer gui, Container container, int recipe) + public Class getGuiClass() + { + return GuiGrinder.class; + } + + @Override + public void drawBackground( int recipe ) + { + GL11.glColor4f( 1, 1, 1, 1 ); + changeTexture( this.getGuiTexture() ); + drawTexturedModalRect( 40, 10, 75, 16 + 10, 90, 66 ); + } + + @Override + public void drawForeground( int recipe ) + { + super.drawForeground( recipe ); + if( this.arecipes.size() > recipe ) + { + CachedRecipe cr = this.arecipes.get( recipe ); + if( cr instanceof CachedGrindStoneRecipe ) + { + CachedGrindStoneRecipe cachedRecipe = (CachedGrindStoneRecipe) cr; + if( cachedRecipe.hasOptional ) + { + FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + int width = fr.getStringWidth( cachedRecipe.Chance ); + fr.drawString( cachedRecipe.Chance, ( 168 - width ) / 2, 5, 0 ); + } + else + { + FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + int width = fr.getStringWidth( GuiText.NoSecondOutput.getLocal() ); + fr.drawString( GuiText.NoSecondOutput.getLocal(), ( 168 - width ) / 2, 5, 0 ); + } + } + } + } + + @Override + public boolean hasOverlay( GuiContainer gui, Container container, int recipe ) { return false; } @Override - public IRecipeOverlayRenderer getOverlayRenderer(GuiContainer gui, int recipe) + public IRecipeOverlayRenderer getOverlayRenderer( GuiContainer gui, int recipe ) { return null; } @Override - public IOverlayHandler getOverlayHandler(GuiContainer gui, int recipe) + public IOverlayHandler getOverlayHandler( GuiContainer gui, int recipe ) { return null; } + @Override + public String getRecipeName() + { + return GuiText.GrindStone.getLocal(); + } + public class CachedGrindStoneRecipe extends TemplateRecipeHandler.CachedRecipe { public final ArrayList ingredients; public final PositionedStack result; - - boolean hasOptional = false; public String Chance; + boolean hasOptional = false; - public CachedGrindStoneRecipe(IGrinderEntry recipe) { + public CachedGrindStoneRecipe( IGrinderEntry recipe ) + { this.result = new PositionedStack( recipe.getOutput(), -30 + 107, 47 ); this.ingredients = new ArrayList(); - if ( recipe.getOptionalOutput() != null ) + if( recipe.getOptionalOutput() != null ) { this.hasOptional = true; - this.Chance = ((int) (recipe.getOptionalChance() * 100)) + GuiText.OfSecondOutput.getLocal(); + this.Chance = ( (int) ( recipe.getOptionalChance() * 100 ) ) + GuiText.OfSecondOutput.getLocal(); this.ingredients.add( new PositionedStack( recipe.getOptionalOutput(), -30 + 107 + 18, 47 ) ); } - if ( recipe.getInput() != null ) + if( recipe.getInput() != null ) this.ingredients.add( new PositionedStack( recipe.getInput(), 45, 24 ) ); } - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIGrinderRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - @Override public PositionedStack getResult() { return this.result; } + @Override + public List getIngredients() + { + return this.getCycledIngredients( NEIGrinderRecipeHandler.this.cycleticks / 20, this.ingredients ); + } + public void computeVisuals() { - for (PositionedStack p : this.ingredients) + for( PositionedStack p : this.ingredients ) { p.generatePermutations(); } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java index 0f625ae28..e01527f8b 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java @@ -18,10 +18,8 @@ package appeng.integration.modules.NEIHelpers; -import static codechicken.lib.gui.GuiDraw.changeTexture; -import static codechicken.lib.gui.GuiDraw.drawTexturedModalRect; -import java.awt.Rectangle; +import java.awt.*; import java.util.ArrayList; import java.util.List; @@ -43,17 +41,13 @@ import appeng.core.localization.GuiText; import appeng.recipes.handlers.Inscribe; import appeng.recipes.handlers.Inscribe.InscriberRecipe; +import static codechicken.lib.gui.GuiDraw.changeTexture; +import static codechicken.lib.gui.GuiDraw.drawTexturedModalRect; + + public class NEIInscriberRecipeHandler extends TemplateRecipeHandler { - @Override - public void drawBackground(int recipe) - { - GL11.glColor4f( 1, 1, 1, 1 ); - changeTexture( this.getGuiTexture() ); - drawTexturedModalRect( 0, 0, 5, 11, 166, 75 ); - } - @Override public void loadTransferRects() { @@ -61,23 +55,11 @@ public class NEIInscriberRecipeHandler extends TemplateRecipeHandler } @Override - public Class getGuiClass() + public void loadCraftingRecipes( String outputId, Object... results ) { - return GuiInscriber.class; - } - - @Override - public String getRecipeName() - { - return GuiText.Inscriber.getLocal(); - } - - @Override - public void loadCraftingRecipes(String outputId, Object... results) - { - if ( (outputId.equals( "inscriber" )) && (this.getClass() == NEIInscriberRecipeHandler.class) ) + if( ( outputId.equals( "inscriber" ) ) && ( this.getClass() == NEIInscriberRecipeHandler.class ) ) { - for (InscriberRecipe recipe : Inscribe.RECIPES ) + for( InscriberRecipe recipe : Inscribe.RECIPES ) { CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); cachedRecipe.computeVisuals(); @@ -91,11 +73,11 @@ public class NEIInscriberRecipeHandler extends TemplateRecipeHandler } @Override - public void loadCraftingRecipes(ItemStack result) + public void loadCraftingRecipes( ItemStack result ) { - for (InscriberRecipe recipe : Inscribe.RECIPES ) + for( InscriberRecipe recipe : Inscribe.RECIPES ) { - if ( NEIServerUtils.areStacksSameTypeCrafting( recipe.output, result ) ) + if( NEIServerUtils.areStacksSameTypeCrafting( recipe.output, result ) ) { CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); cachedRecipe.computeVisuals(); @@ -105,16 +87,16 @@ public class NEIInscriberRecipeHandler extends TemplateRecipeHandler } @Override - public void loadUsageRecipes(ItemStack ingredient) + public void loadUsageRecipes( ItemStack ingredient ) { - for (InscriberRecipe recipe : Inscribe.RECIPES ) + for( InscriberRecipe recipe : Inscribe.RECIPES ) { CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); - if ( (cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() )) ) + if( ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) ) { cachedRecipe.computeVisuals(); - if ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) + if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) { cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); this.arecipes.add( cachedRecipe ); @@ -137,58 +119,79 @@ public class NEIInscriberRecipeHandler extends TemplateRecipeHandler } @Override - public boolean hasOverlay(GuiContainer gui, Container container, int recipe) + public Class getGuiClass() + { + return GuiInscriber.class; + } + + @Override + public void drawBackground( int recipe ) + { + GL11.glColor4f( 1, 1, 1, 1 ); + changeTexture( this.getGuiTexture() ); + drawTexturedModalRect( 0, 0, 5, 11, 166, 75 ); + } + + @Override + public boolean hasOverlay( GuiContainer gui, Container container, int recipe ) { return false; } @Override - public IRecipeOverlayRenderer getOverlayRenderer(GuiContainer gui, int recipe) + public IRecipeOverlayRenderer getOverlayRenderer( GuiContainer gui, int recipe ) { return null; } @Override - public IOverlayHandler getOverlayHandler(GuiContainer gui, int recipe) + public IOverlayHandler getOverlayHandler( GuiContainer gui, int recipe ) { return null; } + @Override + public String getRecipeName() + { + return GuiText.Inscriber.getLocal(); + } + public class CachedInscriberRecipe extends TemplateRecipeHandler.CachedRecipe { public final ArrayList ingredients; public final PositionedStack result; - public CachedInscriberRecipe(InscriberRecipe recipe) { + public CachedInscriberRecipe( InscriberRecipe recipe ) + { this.result = new PositionedStack( recipe.output, 108, 29 ); this.ingredients = new ArrayList(); - if ( recipe.plateA != null ) + if( recipe.plateA != null ) this.ingredients.add( new PositionedStack( recipe.plateA, 40, 5 ) ); - if ( recipe.imprintable != null ) + if( recipe.imprintable != null ) this.ingredients.add( new PositionedStack( recipe.imprintable, 40 + 18, 28 ) ); - if ( recipe.plateB != null ) + if( recipe.plateB != null ) this.ingredients.add( new PositionedStack( recipe.plateB, 40, 51 ) ); } - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIInscriberRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - @Override public PositionedStack getResult() { return this.result; } + @Override + public List getIngredients() + { + return this.getCycledIngredients( NEIInscriberRecipeHandler.this.cycleticks / 20, this.ingredients ); + } + public void computeVisuals() { - for (PositionedStack p : this.ingredients) + for( PositionedStack p : this.ingredients ) { p.generatePermutations(); } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java index 5c1e7e181..8d2c96b3b 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java @@ -18,6 +18,7 @@ package appeng.integration.modules.NEIHelpers; + import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; @@ -48,6 +49,7 @@ import appeng.core.AEConfig; import appeng.core.features.AEFeature; import appeng.core.localization.GuiText; + public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler { @@ -57,61 +59,6 @@ public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler private ItemStack target; - private void addRecipe(IItemDefinition def, String msg) - { - for ( ItemStack definitionStack : def.maybeStack( 1 ).asSet() ) - { - if ( NEIServerUtils.areStacksSameTypeCrafting( definitionStack, this.target ) ) - { - this.offsets.add( def ); - this.outputs.add( new PositionedStack( definitionStack, 75, 4 ) ); - this.details.put( def, msg ); - } - } - } - - private void addRecipes() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IMaterials materials = definitions.materials(); - - final String message; - if ( AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzWorldGen ) ) - { - message = GuiText.ChargedQuartz.getLocal() + "\n\n" + GuiText.ChargedQuartzFind.getLocal(); - } - else - { - message = GuiText.ChargedQuartzFind.getLocal(); - } - - this.addRecipe( materials.certusQuartzCrystalCharged(), message ); - - if ( AEConfig.instance.isFeatureEnabled( AEFeature.MeteoriteWorldGen ) ) - { - this.addRecipe( materials.logicProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - this.addRecipe( materials.calcProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - this.addRecipe( materials.engProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - } - - if ( AEConfig.instance.isFeatureEnabled( AEFeature.inWorldFluix ) ) - { - this.addRecipe( materials.fluixCrystal(), GuiText.inWorldFluix.getLocal() ); - } - - if ( AEConfig.instance.isFeatureEnabled( AEFeature.inWorldSingularity ) ) - { - this.addRecipe( materials.qESingularity(), GuiText.inWorldSingularity.getLocal() ); - } - - if ( AEConfig.instance.isFeatureEnabled( AEFeature.inWorldPurification ) ) - { - this.addRecipe( materials.purifiedCertusQuartzCrystal(), GuiText.inWorldPurificationCertus.getLocal() ); - this.addRecipe( materials.purifiedNetherQuartzCrystal(), GuiText.inWorldPurificationNether.getLocal() ); - this.addRecipe( materials.purifiedFluixCrystal(), GuiText.inWorldPurificationFluix.getLocal() ); - } - } - @Override public String getRecipeName() { @@ -125,15 +72,15 @@ public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler } @Override - public void drawBackground(int recipe) + public void drawBackground( int recipe ) { GL11.glColor4f( 1, 1, 1, 1 );// nothing. } @Override - public void drawForeground(int recipe) + public void drawForeground( int recipe ) { - if ( this.outputs.size() > recipe ) + if( this.outputs.size() > recipe ) { // PositionedStack cr = this.outputs.get( recipe ); String details = this.details.get( this.offsets.get( recipe ) ); @@ -144,19 +91,19 @@ public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler } @Override - public List getIngredientStacks(int recipeIndex) + public List getIngredientStacks( int recipeIndex ) { return new ArrayList(); } @Override - public List getOtherStacks(int recipeIndex) + public List getOtherStacks( int recipeIndex ) { return new ArrayList(); } @Override - public PositionedStack getResultStack(int recipe) + public PositionedStack getResultStack( int recipe ) { return this.outputs.get( recipe ); } @@ -168,19 +115,19 @@ public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler } @Override - public boolean hasOverlay(GuiContainer gui, Container container, int recipe) + public boolean hasOverlay( GuiContainer gui, Container container, int recipe ) { return false; } @Override - public IRecipeOverlayRenderer getOverlayRenderer(GuiContainer gui, int recipe) + public IRecipeOverlayRenderer getOverlayRenderer( GuiContainer gui, int recipe ) { return null; } @Override - public IOverlayHandler getOverlayHandler(GuiContainer gui, int recipe) + public IOverlayHandler getOverlayHandler( GuiContainer gui, int recipe ) { return null; } @@ -192,52 +139,40 @@ public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler } @Override - public List handleTooltip(GuiRecipe gui, List currentToolTip, int recipe) + public List handleTooltip( GuiRecipe gui, List currentToolTip, int recipe ) { return currentToolTip; } @Override - public List handleItemTooltip(GuiRecipe gui, ItemStack stack, List currentToolTip, int recipe) + public List handleItemTooltip( GuiRecipe gui, ItemStack stack, List currentToolTip, int recipe ) { return currentToolTip; } @Override - public boolean keyTyped(GuiRecipe gui, char keyChar, int keyCode, int recipe) + public boolean keyTyped( GuiRecipe gui, char keyChar, int keyCode, int recipe ) { return false; } @Override - public boolean mouseClicked(GuiRecipe gui, int button, int recipe) + public boolean mouseClicked( GuiRecipe gui, int button, int recipe ) { return false; } - public NEIWorldCraftingHandler newInstance() - { - try - { - return this.getClass().newInstance(); - } - catch (Exception e) - { - throw new RuntimeException( e ); - } - } - @Override - public IUsageHandler getUsageHandler(String inputId, Object... ingredients) + public IUsageHandler getUsageHandler( String inputId, Object... ingredients ) { return this; } @Override - public ICraftingHandler getRecipeHandler(String outputId, Object... results) + public ICraftingHandler getRecipeHandler( String outputId, Object... results ) { NEIWorldCraftingHandler g = this.newInstance(); - if ( results.length > 0 && results[0] instanceof ItemStack ) + if( results.length > 0 && results[0] instanceof ItemStack ) { g.target = (ItemStack) results[0]; g.addRecipes(); @@ -246,4 +181,70 @@ public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler return this; } + public NEIWorldCraftingHandler newInstance() + { + try + { + return this.getClass().newInstance(); + } + catch( Exception e ) + { + throw new RuntimeException( e ); + } + } + + private void addRecipes() + { + final IDefinitions definitions = AEApi.instance().definitions(); + final IMaterials materials = definitions.materials(); + + final String message; + if( AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzWorldGen ) ) + { + message = GuiText.ChargedQuartz.getLocal() + "\n\n" + GuiText.ChargedQuartzFind.getLocal(); + } + else + { + message = GuiText.ChargedQuartzFind.getLocal(); + } + + this.addRecipe( materials.certusQuartzCrystalCharged(), message ); + + if( AEConfig.instance.isFeatureEnabled( AEFeature.MeteoriteWorldGen ) ) + { + this.addRecipe( materials.logicProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); + this.addRecipe( materials.calcProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); + this.addRecipe( materials.engProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); + } + + if( AEConfig.instance.isFeatureEnabled( AEFeature.inWorldFluix ) ) + { + this.addRecipe( materials.fluixCrystal(), GuiText.inWorldFluix.getLocal() ); + } + + if( AEConfig.instance.isFeatureEnabled( AEFeature.inWorldSingularity ) ) + { + this.addRecipe( materials.qESingularity(), GuiText.inWorldSingularity.getLocal() ); + } + + if( AEConfig.instance.isFeatureEnabled( AEFeature.inWorldPurification ) ) + { + this.addRecipe( materials.purifiedCertusQuartzCrystal(), GuiText.inWorldPurificationCertus.getLocal() ); + this.addRecipe( materials.purifiedNetherQuartzCrystal(), GuiText.inWorldPurificationNether.getLocal() ); + this.addRecipe( materials.purifiedFluixCrystal(), GuiText.inWorldPurificationFluix.getLocal() ); + } + } + + private void addRecipe( IItemDefinition def, String msg ) + { + for( ItemStack definitionStack : def.maybeStack( 1 ).asSet() ) + { + if( NEIServerUtils.areStacksSameTypeCrafting( definitionStack, this.target ) ) + { + this.offsets.add( def ); + this.outputs.add( new PositionedStack( definitionStack, 75, 4 ) ); + this.details.put( def, msg ); + } + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java b/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java index 7f78aec68..d955a4d27 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java @@ -18,6 +18,7 @@ package appeng.integration.modules.NEIHelpers; + import java.util.ArrayList; import codechicken.nei.PositionedStack; @@ -25,19 +26,19 @@ import codechicken.nei.api.IStackPositioner; import appeng.client.gui.implementations.GuiMEMonitorable; + public class TerminalCraftingSlotFinder implements IStackPositioner { @Override - public ArrayList positionStacks(ArrayList a) + public ArrayList positionStacks( ArrayList a ) { - for (PositionedStack ps : a) - if ( ps != null ) + for( PositionedStack ps : a ) + if( ps != null ) { ps.relx += GuiMEMonitorable.CraftingGridOffsetX; ps.rely += GuiMEMonitorable.CraftingGridOffsetY; } return a; } - } diff --git a/src/main/java/appeng/integration/modules/RB.java b/src/main/java/appeng/integration/modules/RB.java index 18d16b584..245f3514c 100644 --- a/src/main/java/appeng/integration/modules/RB.java +++ b/src/main/java/appeng/integration/modules/RB.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -26,15 +27,39 @@ import rblocks.api.IOrientable; import appeng.integration.BaseModule; import appeng.integration.abstraction.IRB; + public class RB extends BaseModule implements IRB { + public static RB instance; + + @Override + public void init() throws Throwable + { + this.testClassExistence( IOrientable.class ); + } + + @Override + public void postInit() + { + + } + + @Override + public appeng.api.util.IOrientable getOrientable( TileEntity te ) + { + if( te instanceof IOrientable ) + return new RBWrapper( (IOrientable) te ); + return null; + } + private class RBWrapper implements appeng.api.util.IOrientable { final private IOrientable internal; - public RBWrapper(IOrientable ww) { + public RBWrapper( IOrientable ww ) + { this.internal = ww; } @@ -57,33 +82,9 @@ public class RB extends BaseModule implements IRB } @Override - public void setOrientation(ForgeDirection Forward, ForgeDirection Up) + public void setOrientation( ForgeDirection Forward, ForgeDirection Up ) { this.internal.setOrientation( Forward, Up ); } - } - - public static RB instance; - - @Override - public void init() throws Throwable - { - this.testClassExistence( IOrientable.class ); - } - - @Override - public void postInit() - { - - } - - @Override - public appeng.api.util.IOrientable getOrientable(TileEntity te) - { - if ( te instanceof IOrientable ) - return new RBWrapper( (IOrientable) te ); - return null; - } - } diff --git a/src/main/java/appeng/integration/modules/RC.java b/src/main/java/appeng/integration/modules/RC.java index 4f1ed514a..aaef07fb9 100644 --- a/src/main/java/appeng/integration/modules/RC.java +++ b/src/main/java/appeng/integration/modules/RC.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import net.minecraft.item.ItemStack; import mods.railcraft.api.crafting.IRockCrusherRecipe; @@ -26,23 +27,25 @@ import mods.railcraft.api.crafting.RailcraftCraftingManager; import appeng.integration.BaseModule; import appeng.integration.abstraction.IRC; + public class RC extends BaseModule implements IRC { public static RC instance; + public RC() + { + this.testClassExistence( RailcraftCraftingManager.class ); + this.testClassExistence( IRockCrusherRecipe.class ); + } + @Override - public void rockCrusher(ItemStack input, ItemStack output) + public void rockCrusher( ItemStack input, ItemStack output ) { IRockCrusherRecipe re = RailcraftCraftingManager.rockCrusher.createNewRecipe( input, true, true ); re.addOutput( output, 1.0f ); } - public RC() { - this.testClassExistence( RailcraftCraftingManager.class ); - this.testClassExistence( IRockCrusherRecipe.class ); - } - @Override public void init() { diff --git a/src/main/java/appeng/integration/modules/RF.java b/src/main/java/appeng/integration/modules/RF.java index 58e3df6de..ddd8cb253 100644 --- a/src/main/java/appeng/integration/modules/RF.java +++ b/src/main/java/appeng/integration/modules/RF.java @@ -18,6 +18,7 @@ package appeng.integration.modules; + import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; @@ -27,12 +28,14 @@ import appeng.api.AEApi; import appeng.api.config.TunnelType; import appeng.integration.BaseModule; + public class RF extends BaseModule { public static RF instance; - public RF() { + public RF() + { this.testClassExistence( cofh.api.energy.IEnergyReceiver.class ); this.testClassExistence( cofh.api.energy.IEnergyProvider.class ); this.testClassExistence( cofh.api.energy.IEnergyHandler.class ); @@ -44,16 +47,6 @@ public class RF extends BaseModule { } - void RFStack(String mod, String name, int dmg) - { - ItemStack modItem = GameRegistry.findItemStack( mod, name, 1 ); - if ( modItem != null ) - { - modItem.setItemDamage( dmg ); - AEApi.instance().registries().p2pTunnel().addNewAttunement( modItem, TunnelType.RF_POWER ); - } - } - @Override public void postInit() { @@ -70,4 +63,13 @@ public class RF extends BaseModule this.RFStack( "EnderIO", "blockPowerMonitor", 0 ); } + void RFStack( String mod, String name, int dmg ) + { + ItemStack modItem = GameRegistry.findItemStack( mod, name, 1 ); + if( modItem != null ) + { + modItem.setItemDamage( dmg ); + AEApi.instance().registries().p2pTunnel().addNewAttunement( modItem, TunnelType.RF_POWER ); + } + } } diff --git a/src/main/java/appeng/integration/modules/RFItem.java b/src/main/java/appeng/integration/modules/RFItem.java index e232e29f7..ec5abb76f 100644 --- a/src/main/java/appeng/integration/modules/RFItem.java +++ b/src/main/java/appeng/integration/modules/RFItem.java @@ -18,14 +18,17 @@ package appeng.integration.modules; + import appeng.integration.BaseModule; + public class RFItem extends BaseModule { public static RFItem instance; - public RFItem() { + public RFItem() + { this.testClassExistence( cofh.api.energy.IEnergyContainerItem.class ); } @@ -40,5 +43,4 @@ public class RFItem extends BaseModule { } - } diff --git a/src/main/java/appeng/integration/modules/helpers/BSCrate.java b/src/main/java/appeng/integration/modules/helpers/BSCrate.java index f79aac13e..475b76907 100644 --- a/src/main/java/appeng/integration/modules/helpers/BSCrate.java +++ b/src/main/java/appeng/integration/modules/helpers/BSCrate.java @@ -46,11 +46,11 @@ public class BSCrate implements IMEInventory @Override public IAEItemStack injectItems( IAEItemStack input, Actionable mode, BaseActionSource src ) { - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) return null; ItemStack failed = this.crateStorage.insertItems( input.getItemStack() ); - if ( failed == null ) + if( failed == null ) return null; input.setStackSize( failed.stackSize ); return input; @@ -59,7 +59,7 @@ public class BSCrate implements IMEInventory @Override public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) { - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) { int howMany = this.crateStorage.getItemCount( request.getItemStack() ); return howMany > request.getStackSize() ? request : request.copy().setStackSize( howMany ); @@ -72,7 +72,7 @@ public class BSCrate implements IMEInventory @Override public IItemList getAvailableItems( IItemList out ) { - for ( ItemStack is : this.crateStorage.getContents() ) + for( ItemStack is : this.crateStorage.getContents() ) { out.add( AEItemStack.create( is ) ); } diff --git a/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java b/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java index 6aa18a120..f50efca95 100644 --- a/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java @@ -18,6 +18,7 @@ package appeng.integration.modules.helpers; + import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -27,21 +28,21 @@ import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; import appeng.api.storage.StorageChannel; + public class BSCrateHandler implements IExternalStorageHandler { @Override - public boolean canHandle(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc) + public boolean canHandle( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc ) { return channel == StorageChannel.ITEMS && te instanceof ICrateStorage; } @Override - public IMEInventory getInventory(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src) + public IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src ) { - if ( channel == StorageChannel.ITEMS ) + if( channel == StorageChannel.ITEMS ) return new BSCrate( te, ForgeDirection.UNKNOWN ); return null; } - } diff --git a/src/main/java/appeng/integration/modules/helpers/BSCrateStorageAdaptor.java b/src/main/java/appeng/integration/modules/helpers/BSCrateStorageAdaptor.java index ebc07c44f..474c2c663 100644 --- a/src/main/java/appeng/integration/modules/helpers/BSCrateStorageAdaptor.java +++ b/src/main/java/appeng/integration/modules/helpers/BSCrateStorageAdaptor.java @@ -18,6 +18,7 @@ package appeng.integration.modules.helpers; + import java.util.Iterator; import net.mcft.copy.betterstorage.api.crate.ICrateStorage; @@ -31,29 +32,31 @@ import appeng.util.inv.IInventoryDestination; import appeng.util.inv.ItemSlot; import appeng.util.iterators.StackToSlotIterator; + public class BSCrateStorageAdaptor extends InventoryAdaptor { final ICrateStorage cs; final ForgeDirection side; - public BSCrateStorageAdaptor(Object te, ForgeDirection d) { + public BSCrateStorageAdaptor( Object te, ForgeDirection d ) + { this.cs = (ICrateStorage) te; this.side = d; } @Override - public ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination) + public ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ) { ItemStack target = null; - for (ItemStack is : this.cs.getContents()) + for( ItemStack is : this.cs.getContents() ) { - if ( is != null ) + if( is != null ) { - if ( is.stackSize > 0 && ( filter == null || Platform.isSameItem( filter, is )) ) + if( is.stackSize > 0 && ( filter == null || Platform.isSameItem( filter, is ) ) ) { - if ( destination == null || destination.canInsert( is ) ) + if( destination == null || destination.canInsert( is ) ) { target = is; break; @@ -62,7 +65,7 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor } } - if ( target != null ) + if( target != null ) { ItemStack f = Platform.cloneItemStack( target ); f.stackSize = amount; @@ -73,17 +76,17 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor } @Override - public ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination) + public ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ) { ItemStack target = null; - for (ItemStack is : this.cs.getContents()) + for( ItemStack is : this.cs.getContents() ) { - if ( is != null ) + if( is != null ) { - if ( is.stackSize > 0 && ( filter == null || Platform.isSameItem( filter, is )) ) + if( is.stackSize > 0 && ( filter == null || Platform.isSameItem( filter, is ) ) ) { - if ( destination == null || destination.canInsert( is ) ) + if( destination == null || destination.canInsert( is ) ) { target = is; break; @@ -92,12 +95,12 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor } } - if ( target != null ) + if( target != null ) { int cnt = this.cs.getItemCount( target ); - if ( cnt == 0 ) + if( cnt == 0 ) return null; - if ( cnt > amount ) + if( cnt > amount ) cnt = amount; ItemStack c = target.copy(); c.stackSize = cnt; @@ -108,17 +111,17 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor } @Override - public ItemStack removeSimilarItems(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) + public ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) { ItemStack target = null; - for (ItemStack is : this.cs.getContents()) + for( ItemStack is : this.cs.getContents() ) { - if ( is != null ) + if( is != null ) { - if ( is.stackSize > 0 && (filter == null || Platform.isSameItemFuzzy( filter, is, fuzzyMode )) ) + if( is.stackSize > 0 && ( filter == null || Platform.isSameItemFuzzy( filter, is, fuzzyMode ) ) ) { - if ( destination == null || destination.canInsert( is ) ) + if( destination == null || destination.canInsert( is ) ) { target = is; break; @@ -127,7 +130,7 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor } } - if ( target != null ) + if( target != null ) { ItemStack f = Platform.cloneItemStack( target ); f.stackSize = amount; @@ -138,17 +141,17 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor } @Override - public ItemStack simulateSimilarRemove(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) + public ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) { ItemStack target = null; - for (ItemStack is : this.cs.getContents()) + for( ItemStack is : this.cs.getContents() ) { - if ( is != null ) + if( is != null ) { - if ( is.stackSize > 0 && (filter == null || Platform.isSameItemFuzzy( filter, is, fuzzyMode )) ) + if( is.stackSize > 0 && ( filter == null || Platform.isSameItemFuzzy( filter, is, fuzzyMode ) ) ) { - if ( destination == null || destination.canInsert( is ) ) + if( destination == null || destination.canInsert( is ) ) { target = is; break; @@ -157,12 +160,12 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor } } - if ( target != null ) + if( target != null ) { int cnt = this.cs.getItemCount( target ); - if ( cnt == 0 ) + if( cnt == 0 ) return null; - if ( cnt > amount ) + if( cnt > amount ) cnt = amount; ItemStack c = target.copy(); c.stackSize = cnt; @@ -173,17 +176,17 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor } @Override - public ItemStack addItems(ItemStack toBeAdded ) + public ItemStack addItems( ItemStack toBeAdded ) { return this.cs.insertItems( toBeAdded ); } @Override - public ItemStack simulateAdd(ItemStack toBeSimulated ) + public ItemStack simulateAdd( ItemStack toBeSimulated ) { int items = this.cs.getSpaceForItem( toBeSimulated ); ItemStack B = Platform.cloneItemStack( toBeSimulated ); - if ( toBeSimulated.stackSize <= items ) + if( toBeSimulated.stackSize <= items ) return null; B.stackSize -= items; return B; @@ -200,5 +203,4 @@ public class BSCrateStorageAdaptor extends InventoryAdaptor { return new StackToSlotIterator( this.cs.getContents().iterator() ); } - } diff --git a/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java b/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java index 1533cbdd1..e043452f5 100644 --- a/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java +++ b/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java @@ -18,17 +18,19 @@ package appeng.integration.modules.helpers; + import net.minecraft.entity.player.EntityPlayerMP; import cpw.mods.fml.common.eventhandler.Event; + public class FMPPacketEvent extends Event { public final EntityPlayerMP sender; - public FMPPacketEvent(EntityPlayerMP sender) { + public FMPPacketEvent( EntityPlayerMP sender ) + { this.sender = sender; } - } diff --git a/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java b/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java index 9b661f0a5..cbebe4f8a 100644 --- a/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java +++ b/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java @@ -18,6 +18,7 @@ package appeng.integration.modules.helpers; + import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -30,39 +31,76 @@ import appeng.api.storage.data.IItemList; import appeng.integration.abstraction.IFZ; import appeng.util.item.AEItemStack; + public class FactorizationBarrel implements IMEInventory { - private final TileEntity te; final IFZ fProxy; + private final TileEntity te; - public FactorizationBarrel(IFZ proxy, TileEntity tile) { + public FactorizationBarrel( IFZ proxy, TileEntity tile ) + { this.te = tile; this.fProxy = proxy; } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - public long remainingItemTypes() - { - return this.fProxy.barrelGetItem( this.te ) == null ? 1 : 0; - } - public long remainingItemCount() { return this.fProxy.barrelGetMaxItemCount( this.te ) - this.fProxy.barrelGetItemCount( this.te ); } - public boolean containsItemType(IAEItemStack i, boolean acceptEmpty) + @Override + public IAEItemStack injectItems( IAEItemStack input, Actionable mode, BaseActionSource src ) + { + if( input == null ) + return null; + if( input.getStackSize() == 0 ) + return null; + + ItemStack shared = input.getItemStack(); + if( shared.isItemDamaged() ) + return input; + + if( this.remainingItemTypes() > 0 ) + { + if( mode == Actionable.MODULATE ) + this.fProxy.setItemType( this.te, input.getItemStack() ); + } + + if( this.containsItemType( input, mode == Actionable.SIMULATE ) ) + { + int max = this.fProxy.barrelGetMaxItemCount( this.te ); + int newTotal = (int) this.storedItemCount() + (int) input.getStackSize(); + if( newTotal > max ) + { + if( mode == Actionable.MODULATE ) + this.fProxy.barrelSetCount( this.te, max ); + IAEItemStack result = input.copy(); + result.setStackSize( newTotal - max ); + return result; + } + else + { + if( mode == Actionable.MODULATE ) + this.fProxy.barrelSetCount( this.te, newTotal ); + return null; + } + } + + return input; + } + + public long remainingItemTypes() + { + return this.fProxy.barrelGetItem( this.te ) == null ? 1 : 0; + } + + public boolean containsItemType( IAEItemStack i, boolean acceptEmpty ) { ItemStack currentItem = this.fProxy.barrelGetItem( this.te ); // empty barrels want your love too! - if ( acceptEmpty && currentItem == null ) + if( acceptEmpty && currentItem == null ) return true; return i.equals( currentItem ); @@ -74,55 +112,14 @@ public class FactorizationBarrel implements IMEInventory } @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable mode, BaseActionSource src) + public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) { - if ( input == null ) - return null; - if ( input.getStackSize() == 0 ) - return null; - - ItemStack shared = input.getItemStack(); - if ( shared.isItemDamaged() ) - return input; - - if ( this.remainingItemTypes() > 0 ) - { - if ( mode == Actionable.MODULATE ) - this.fProxy.setItemType( this.te, input.getItemStack() ); - } - - if ( this.containsItemType( input, mode == Actionable.SIMULATE ) ) - { - int max = this.fProxy.barrelGetMaxItemCount( this.te ); - int newTotal = (int) this.storedItemCount() + (int) input.getStackSize(); - if ( newTotal > max ) - { - if ( mode == Actionable.MODULATE ) - this.fProxy.barrelSetCount( this.te, max ); - IAEItemStack result = input.copy(); - result.setStackSize( newTotal - max ); - return result; - } - else - { - if ( mode == Actionable.MODULATE ) - this.fProxy.barrelSetCount( this.te, newTotal ); - return null; - } - } - - return input; - } - - @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) - { - if ( this.containsItemType( request, false ) ) + if( this.containsItemType( request, false ) ) { int howMany = (int) this.storedItemCount(); - if ( request.getStackSize() >= howMany ) + if( request.getStackSize() >= howMany ) { - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) { this.fProxy.setItemType( this.te, null ); this.fProxy.barrelSetCount( this.te, 0 ); @@ -134,8 +131,8 @@ public class FactorizationBarrel implements IMEInventory } else { - if ( mode == Actionable.MODULATE ) - this.fProxy.barrelSetCount( this.te, (int) (howMany - request.getStackSize()) ); + if( mode == Actionable.MODULATE ) + this.fProxy.barrelSetCount( this.te, (int) ( howMany - request.getStackSize() ) ); return request.copy(); } } @@ -143,10 +140,10 @@ public class FactorizationBarrel implements IMEInventory } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { ItemStack i = this.fProxy.barrelGetItem( this.te ); - if ( i != null ) + if( i != null ) { i.stackSize = this.fProxy.barrelGetItemCount( this.te ); out.addStorage( AEItemStack.create( i ) ); @@ -155,4 +152,9 @@ public class FactorizationBarrel implements IMEInventory return out; } + @Override + public StorageChannel getChannel() + { + return StorageChannel.ITEMS; + } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java b/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java index 153a4600b..2aa98081c 100644 --- a/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java @@ -18,6 +18,7 @@ package appeng.integration.modules.helpers; + import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -29,21 +30,21 @@ import appeng.integration.modules.FZ; import appeng.me.storage.MEMonitorIInventory; import appeng.util.inv.IMEAdaptor; + public class FactorizationHandler implements IExternalStorageHandler { @Override - public boolean canHandle(TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource mySrc) + public boolean canHandle( TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource mySrc ) { return chan == StorageChannel.ITEMS && FZ.instance.isBarrel( te ); } @Override - public IMEInventory getInventory(TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource src) + public IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource src ) { - if ( chan == StorageChannel.ITEMS ) + if( chan == StorageChannel.ITEMS ) return new MEMonitorIInventory( new IMEAdaptor( FZ.instance.getFactorizationBarrel( te ), src ) ); return null; } - } diff --git a/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java b/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java index 93faa73df..ed9cdc304 100644 --- a/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java @@ -18,6 +18,7 @@ package appeng.integration.modules.helpers; + import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -29,19 +30,20 @@ import appeng.integration.modules.DSU; import appeng.me.storage.MEMonitorIInventory; import appeng.util.inv.IMEAdaptor; + public class MFRDSUHandler implements IExternalStorageHandler { @Override - public boolean canHandle(TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource mySrc) + public boolean canHandle( TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource mySrc ) { return chan == StorageChannel.ITEMS && DSU.instance.isDSU( te ); } @Override - public IMEInventory getInventory(TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource src) + public IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel chan, BaseActionSource src ) { - if ( chan == StorageChannel.ITEMS ) + if( chan == StorageChannel.ITEMS ) return new MEMonitorIInventory( new IMEAdaptor( DSU.instance.getDSU( te ), src ) ); return null; diff --git a/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java b/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java index daa562327..550d70e8c 100644 --- a/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java +++ b/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java @@ -18,6 +18,7 @@ package appeng.integration.modules.helpers; + import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -31,48 +32,44 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.util.item.AEItemStack; + public class MinefactoryReloadedDeepStorageUnit implements IMEInventory { final IDeepStorageUnit dsu; final TileEntity te; - public MinefactoryReloadedDeepStorageUnit(TileEntity ta) { + public MinefactoryReloadedDeepStorageUnit( TileEntity ta ) + { this.te = ta; this.dsu = (IDeepStorageUnit) ta; } @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable mode, BaseActionSource src) + public IAEItemStack injectItems( IAEItemStack input, Actionable mode, BaseActionSource src ) { ItemStack is = this.dsu.getStoredItemType(); - if ( is != null ) + if( is != null ) { - if ( input.equals( is ) ) + if( input.equals( is ) ) { long max = this.dsu.getMaxStoredCount(); long storedItems = is.stackSize; - if ( max == storedItems ) + if( max == storedItems ) return input; storedItems += input.getStackSize(); - if ( storedItems > max ) + if( storedItems > max ) { IAEItemStack overflow = AEItemStack.create( is ); - overflow.setStackSize( (int) (storedItems - max) ); - if ( mode == Actionable.MODULATE ) + overflow.setStackSize( (int) ( storedItems - max ) ); + if( mode == Actionable.MODULATE ) this.dsu.setStoredItemCount( (int) max ); return overflow; } else { - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) this.dsu.setStoredItemCount( is.stackSize + (int) input.getStackSize() ); return null; } @@ -80,9 +77,9 @@ public class MinefactoryReloadedDeepStorageUnit implements IMEInventory= is.stackSize ) + if( request.getStackSize() >= is.stackSize ) { is = is.copy(); - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) this.dsu.setStoredItemCount( 0 ); return AEItemStack.create( is ); } else { - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) this.dsu.setStoredItemCount( is.stackSize - (int) request.getStackSize() ); return request.copy(); } @@ -113,14 +110,19 @@ public class MinefactoryReloadedDeepStorageUnit implements IMEInventory getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { ItemStack is = this.dsu.getStoredItemType(); - if ( is != null ) + if( is != null ) { out.add( AEItemStack.create( is ) ); } return out; } + @Override + public StorageChannel getChannel() + { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java index bc021c382..73e35e7d0 100644 --- a/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java @@ -93,11 +93,11 @@ public final class PartWailaDataProvider implements IWailaDataProvider final Optional maybePart = this.accessor.getMaybePart( te, mop ); - if ( maybePart.isPresent() ) + if( maybePart.isPresent() ) { final IPart part = maybePart.get(); - for ( IPartWailaDataProvider provider : this.providers ) + for( IPartWailaDataProvider provider : this.providers ) { provider.getWailaHead( part, currentToolTip, accessor, config ); } @@ -114,11 +114,11 @@ public final class PartWailaDataProvider implements IWailaDataProvider final Optional maybePart = this.accessor.getMaybePart( te, mop ); - if ( maybePart.isPresent() ) + if( maybePart.isPresent() ) { final IPart part = maybePart.get(); - for ( IPartWailaDataProvider provider : this.providers ) + for( IPartWailaDataProvider provider : this.providers ) { provider.getWailaBody( part, currentToolTip, accessor, config ); } @@ -135,11 +135,11 @@ public final class PartWailaDataProvider implements IWailaDataProvider final Optional maybePart = this.accessor.getMaybePart( te, mop ); - if ( maybePart.isPresent() ) + if( maybePart.isPresent() ) { final IPart part = maybePart.get(); - for ( IPartWailaDataProvider provider : this.providers ) + for( IPartWailaDataProvider provider : this.providers ) { provider.getWailaTail( part, currentToolTip, accessor, config ); } @@ -153,15 +153,15 @@ public final class PartWailaDataProvider implements IWailaDataProvider { final MovingObjectPosition mop = this.tracer.retraceBlock( world, player, x, y, z ); - if ( mop != null ) + if( mop != null ) { final Optional maybePart = this.accessor.getMaybePart( te, mop ); - if ( maybePart.isPresent() ) + if( maybePart.isPresent() ) { final IPart part = maybePart.get(); - for ( IPartWailaDataProvider provider : this.providers ) + for( IPartWailaDataProvider provider : this.providers ) { provider.getNBTData( player, part, te, tag, world, x, y, z ); } diff --git a/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java index 5ce333fd3..80ccfed91 100644 --- a/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java @@ -74,7 +74,7 @@ public final class TileWailaDataProvider implements IWailaDataProvider @Override public List getWailaHead( ItemStack itemStack, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { - for ( IWailaDataProvider provider : this.providers ) + for( IWailaDataProvider provider : this.providers ) { provider.getWailaHead( itemStack, currentToolTip, accessor, config ); } @@ -85,7 +85,7 @@ public final class TileWailaDataProvider implements IWailaDataProvider @Override public List getWailaBody( ItemStack itemStack, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { - for ( IWailaDataProvider provider : this.providers ) + for( IWailaDataProvider provider : this.providers ) { provider.getWailaBody( itemStack, currentToolTip, accessor, config ); } @@ -96,7 +96,7 @@ public final class TileWailaDataProvider implements IWailaDataProvider @Override public List getWailaTail( ItemStack itemStack, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { - for ( IWailaDataProvider provider : this.providers ) + for( IWailaDataProvider provider : this.providers ) { provider.getWailaTail( itemStack, currentToolTip, accessor, config ); } @@ -107,7 +107,7 @@ public final class TileWailaDataProvider implements IWailaDataProvider @Override public NBTTagCompound getNBTData( EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z ) { - for ( IWailaDataProvider provider : this.providers ) + for( IWailaDataProvider provider : this.providers ) { provider.getNBTData( player, te, tag, world, x, y, z ); } diff --git a/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java index dcc16dd7a..23dbf82b5 100644 --- a/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java @@ -75,12 +75,12 @@ public final class ChannelWailaDataProvider extends BasePartWailaDataProvider @Override public List getWailaBody( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { - if ( part instanceof PartCableSmart || part instanceof PartDenseCable ) + if( part instanceof PartCableSmart || part instanceof PartDenseCable ) { final NBTTagCompound tag = accessor.getNBTData(); final byte usedChannels = this.getUsedChannels( part, tag, this.cache ); - final byte maxChannels = ( byte ) ( ( part instanceof PartDenseCable ) ? 32 : 8 ); + final byte maxChannels = (byte) ( ( part instanceof PartDenseCable ) ? 32 : 8 ); currentToolTip.add( usedChannels + " " + GuiText.Of.getLocal() + ' ' + maxChannels + ' ' + WailaText.Channels.getLocal() ); } @@ -105,12 +105,12 @@ public final class ChannelWailaDataProvider extends BasePartWailaDataProvider { final byte usedChannels; - if ( tag.hasKey( ID_USED_CHANNELS ) ) + if( tag.hasKey( ID_USED_CHANNELS ) ) { usedChannels = tag.getByte( ID_USED_CHANNELS ); this.cache.put( part, usedChannels ); } - else if ( this.cache.containsKey( part ) ) + else if( this.cache.containsKey( part ) ) { usedChannels = this.cache.get( part ); } @@ -143,13 +143,13 @@ public final class ChannelWailaDataProvider extends BasePartWailaDataProvider @Override public NBTTagCompound getNBTData( EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z ) { - if ( part instanceof PartCableSmart || part instanceof PartDenseCable ) + if( part instanceof PartCableSmart || part instanceof PartDenseCable ) { final NBTTagCompound tempTag = new NBTTagCompound(); part.writeToNBT( tempTag ); - if ( tempTag.hasKey( ID_USED_CHANNELS ) ) + if( tempTag.hasKey( ID_USED_CHANNELS ) ) { final byte usedChannels = tempTag.getByte( ID_USED_CHANNELS ); diff --git a/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java index fa1e91407..d6a79f7f7 100644 --- a/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java @@ -47,5 +47,5 @@ public interface IPartWailaDataProvider List getWailaTail( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); - NBTTagCompound getNBTData(EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z); + NBTTagCompound getNBTData( EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z ); } diff --git a/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java b/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java index 107e904c4..2fbc61479 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java +++ b/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java @@ -52,13 +52,13 @@ public final class PartAccessor */ public Optional getMaybePart( TileEntity te, MovingObjectPosition mop ) { - if ( te instanceof IPartHost ) + if( te instanceof IPartHost ) { final Vec3 position = mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ); - final IPartHost host = ( IPartHost ) te; + final IPartHost host = (IPartHost) te; final SelectedPart sp = host.selectPart( position ); - if ( sp.part != null ) + if( sp.part != null ) { return Optional.of( sp.part ); } diff --git a/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java index 59bc2fba1..ce976fad9 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java @@ -51,9 +51,9 @@ public final class PowerStateWailaDataProvider extends BasePartWailaDataProvider @Override public List getWailaBody( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { - if ( part instanceof IPowerChannelState ) + if( part instanceof IPowerChannelState ) { - final IPowerChannelState state = ( IPowerChannelState ) part; + final IPowerChannelState state = (IPowerChannelState) part; currentToolTip.add( this.getToolTip( state.isActive(), state.isPowered() ) ); } @@ -73,11 +73,11 @@ public final class PowerStateWailaDataProvider extends BasePartWailaDataProvider { final String result; - if ( isActive && isPowered ) + if( isActive && isPowered ) { result = WailaText.DeviceOnline.getLocal(); } - else if ( isPowered ) + else if( isPowered ) { result = WailaText.DeviceMissingChannel.getLocal(); } diff --git a/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java index 3743a3276..dfd96a9cf 100644 --- a/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java @@ -55,21 +55,21 @@ public final class StorageMonitorWailaDataProvider extends BasePartWailaDataProv @Override public List getWailaBody( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { - if ( part instanceof IPartStorageMonitor ) + if( part instanceof IPartStorageMonitor ) { - final IPartStorageMonitor monitor = ( IPartStorageMonitor ) part; + final IPartStorageMonitor monitor = (IPartStorageMonitor) part; final IAEStack displayed = monitor.getDisplayed(); final boolean isLocked = monitor.isLocked(); - if ( displayed instanceof IAEItemStack ) + if( displayed instanceof IAEItemStack ) { - IAEItemStack ais = ( IAEItemStack ) displayed; + IAEItemStack ais = (IAEItemStack) displayed; currentToolTip.add( WailaText.Showing.getLocal() + ": " + ais.getItemStack().getDisplayName() ); } - else if ( displayed instanceof IAEFluidStack ) + else if( displayed instanceof IAEFluidStack ) { - IAEFluidStack ais = ( IAEFluidStack ) displayed; + IAEFluidStack ais = (IAEFluidStack) displayed; currentToolTip.add( WailaText.Showing.getLocal() + ": " + ais.getFluid().getLocalizedName( ais.getFluidStack() ) ); } diff --git a/src/main/java/appeng/integration/modules/waila/part/Tracer.java b/src/main/java/appeng/integration/modules/waila/part/Tracer.java index 0f2baab76..129d409bf 100644 --- a/src/main/java/appeng/integration/modules/waila/part/Tracer.java +++ b/src/main/java/appeng/integration/modules/waila/part/Tracer.java @@ -40,11 +40,11 @@ public final class Tracer * Trace view of players to blocks. * Ignore all which are out of reach. * - * @param world word of block + * @param world word of block * @param player player viewing block - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block * * @return trace movement. Can be null */ @@ -70,7 +70,7 @@ public final class Tracer private Vec3 getCorrectedHeadVec( EntityPlayer player ) { Vec3 v = Vec3.createVectorHelper( player.posX, player.posY, player.posZ ); - if ( player.worldObj.isRemote ) + if( player.worldObj.isRemote ) { //compatibility with eye height changing mods v.yCoord += player.getEyeHeight() - player.getDefaultEyeHeight(); @@ -78,7 +78,7 @@ public final class Tracer else { v.yCoord += player.getEyeHeight(); - if ( player instanceof EntityPlayerMP && player.isSneaking() ) + if( player instanceof EntityPlayerMP && player.isSneaking() ) v.yCoord -= 0.08; } return v; diff --git a/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java index 6fb5bcad4..047b05bc4 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java @@ -57,13 +57,13 @@ public final class ChargerWailaDataProvider extends BaseWailaDataProvider public List getWailaBody( ItemStack itemStack, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { final TileEntity te = accessor.getTileEntity(); - if ( te instanceof TileCharger ) + if( te instanceof TileCharger ) { - final TileCharger charger = ( TileCharger ) te; + final TileCharger charger = (TileCharger) te; final IInventory chargerInventory = charger.getInternalInventory(); final ItemStack chargingItem = chargerInventory.getStackInSlot( 0 ); - if ( chargingItem != null ) + if( chargingItem != null ) { final String currentInventory = chargingItem.getDisplayName(); final EntityPlayer player = accessor.getPlayer(); diff --git a/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java index dd3a24be3..2267c7f22 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java @@ -56,12 +56,12 @@ public final class CraftingMonitorWailaDataProvider extends BaseWailaDataProvide public List getWailaBody( ItemStack itemStack, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { final TileEntity te = accessor.getTileEntity(); - if ( te instanceof TileCraftingMonitorTile ) + if( te instanceof TileCraftingMonitorTile ) { - final TileCraftingMonitorTile monitor = ( TileCraftingMonitorTile ) te; + final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) te; final IAEItemStack displayStack = monitor.getJobProgress(); - if ( displayStack != null ) + if( displayStack != null ) { final String currentCrafting = displayStack.getItemStack().getDisplayName(); diff --git a/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java index 9458ca91f..9c74fd8b7 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java @@ -56,18 +56,18 @@ public final class PowerStateWailaDataProvider extends BaseWailaDataProvider { final TileEntity te = accessor.getTileEntity(); - if ( te instanceof IPowerChannelState ) + if( te instanceof IPowerChannelState ) { - final IPowerChannelState state = ( IPowerChannelState ) te; + final IPowerChannelState state = (IPowerChannelState) te; final boolean isActive = state.isActive(); final boolean isPowered = state.isPowered(); - if ( isActive && isPowered ) + if( isActive && isPowered ) { currentToolTip.add( WailaText.DeviceOnline.getLocal() ); } - else if ( isPowered ) + else if( isPowered ) { currentToolTip.add( WailaText.DeviceMissingChannel.getLocal() ); } diff --git a/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java index 7f86fa689..8580a8d60 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java @@ -77,17 +77,17 @@ public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider public List getWailaBody( ItemStack itemStack, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ) { final TileEntity te = accessor.getTileEntity(); - if ( te instanceof IAEPowerStorage ) + if( te instanceof IAEPowerStorage ) { - final IAEPowerStorage storage = ( IAEPowerStorage ) te; + final IAEPowerStorage storage = (IAEPowerStorage) te; final double maxPower = storage.getAEMaxPower(); - if ( maxPower > 0 ) + if( maxPower > 0 ) { final NBTTagCompound tag = accessor.getNBTData(); final long internalCurrentPower = this.getInternalCurrentPower( tag, te ); - final long internalMaxPower = ( long ) ( 100 * maxPower ); + final long internalMaxPower = (long) ( 100 * maxPower ); final String formatCurrentPower = Platform.formatPowerLong( internalCurrentPower, false ); final String formatMaxPower = Platform.formatPowerLong( internalMaxPower, false ); @@ -119,13 +119,13 @@ public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider @Override public NBTTagCompound getNBTData( EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z ) { - if ( te instanceof IAEPowerStorage ) + if( te instanceof IAEPowerStorage ) { - final IAEPowerStorage storage = ( IAEPowerStorage ) te; + final IAEPowerStorage storage = (IAEPowerStorage) te; - if ( storage.getAEMaxPower() > 0 ) + if( storage.getAEMaxPower() > 0 ) { - final long internalCurrentPower = ( long ) ( 100 * storage.getAECurrentPower() ); + final long internalCurrentPower = (long) ( 100 * storage.getAECurrentPower() ); tag.setLong( ID_CURRENT_POWER, internalCurrentPower ); } @@ -150,12 +150,12 @@ public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider { final long internalCurrentPower; - if ( tag.hasKey( ID_CURRENT_POWER ) ) + if( tag.hasKey( ID_CURRENT_POWER ) ) { internalCurrentPower = tag.getLong( ID_CURRENT_POWER ); this.cache.put( te, internalCurrentPower ); } - else if ( this.cache.containsKey( te ) ) + else if( this.cache.containsKey( te ) ) { internalCurrentPower = this.cache.get( te ); } diff --git a/src/main/java/appeng/items/AEBaseItem.java b/src/main/java/appeng/items/AEBaseItem.java index afe1b6c47..75464aa99 100644 --- a/src/main/java/appeng/items/AEBaseItem.java +++ b/src/main/java/appeng/items/AEBaseItem.java @@ -43,7 +43,7 @@ public abstract class AEBaseItem extends Item implements IAEFeature public AEBaseItem() { - this( Optional. absent() ); + this( Optional.absent() ); this.setNoRepair(); } diff --git a/src/main/java/appeng/items/contents/CellConfig.java b/src/main/java/appeng/items/contents/CellConfig.java index a84b5dc85..be8f63a0d 100644 --- a/src/main/java/appeng/items/contents/CellConfig.java +++ b/src/main/java/appeng/items/contents/CellConfig.java @@ -18,17 +18,20 @@ package appeng.items.contents; + import net.minecraft.item.ItemStack; import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; + public class CellConfig extends AppEngInternalInventory { final ItemStack is; - public CellConfig(ItemStack is) { + public CellConfig( ItemStack is ) + { super( null, 63 ); this.is = is; this.readFromNBT( Platform.openNbtData( is ), "list" ); @@ -39,5 +42,4 @@ public class CellConfig extends AppEngInternalInventory { this.writeToNBT( Platform.openNbtData( this.is ), "list" ); } - } \ No newline at end of file diff --git a/src/main/java/appeng/items/contents/NetworkToolViewer.java b/src/main/java/appeng/items/contents/NetworkToolViewer.java index e6ddeede5..73ef3427b 100644 --- a/src/main/java/appeng/items/contents/NetworkToolViewer.java +++ b/src/main/java/appeng/items/contents/NetworkToolViewer.java @@ -18,6 +18,7 @@ package appeng.items.contents; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -27,6 +28,7 @@ import appeng.api.networking.IGridHost; import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; + public class NetworkToolViewer implements INetworkTool { @@ -34,11 +36,12 @@ public class NetworkToolViewer implements INetworkTool final ItemStack is; final IGridHost gh; - public NetworkToolViewer(ItemStack is, IGridHost gHost) { + public NetworkToolViewer( ItemStack is, IGridHost gHost ) + { this.is = is; this.gh = gHost; this.inv = new AppEngInternalInventory( null, 9 ); - if ( is.hasTagCompound() ) // prevent crash when opening network status screen. + if( is.hasTagCompound() ) // prevent crash when opening network status screen. this.inv.readFromNBT( Platform.openNbtData( is ), "inv" ); } @@ -49,25 +52,25 @@ public class NetworkToolViewer implements INetworkTool } @Override - public ItemStack getStackInSlot(int i) + public ItemStack getStackInSlot( int i ) { return this.inv.getStackInSlot( i ); } @Override - public ItemStack decrStackSize(int i, int j) + public ItemStack decrStackSize( int i, int j ) { return this.inv.decrStackSize( i, j ); } @Override - public ItemStack getStackInSlotOnClosing(int i) + public ItemStack getStackInSlotOnClosing( int i ) { return this.inv.getStackInSlotOnClosing( i ); } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public void setInventorySlotContents( int i, ItemStack itemstack ) { this.inv.setInventorySlotContents( i, itemstack ); } @@ -98,7 +101,7 @@ public class NetworkToolViewer implements INetworkTool } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) + public boolean isUseableByPlayer( EntityPlayer entityplayer ) { return this.inv.isUseableByPlayer( entityplayer ); } @@ -116,10 +119,9 @@ public class NetworkToolViewer implements INetworkTool } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { - return this.inv.isItemValidForSlot( i, itemstack ) && itemstack.getItem() instanceof IUpgradeModule - && ((IUpgradeModule) itemstack.getItem()).getType( itemstack ) != null; + return this.inv.isItemValidForSlot( i, itemstack ) && itemstack.getItem() instanceof IUpgradeModule && ( (IUpgradeModule) itemstack.getItem() ).getType( itemstack ) != null; } @Override @@ -133,5 +135,4 @@ public class NetworkToolViewer implements INetworkTool { return this.gh; } - } diff --git a/src/main/java/appeng/items/contents/PortableCellViewer.java b/src/main/java/appeng/items/contents/PortableCellViewer.java index 4fa2ca929..98d9a3536 100644 --- a/src/main/java/appeng/items/contents/PortableCellViewer.java +++ b/src/main/java/appeng/items/contents/PortableCellViewer.java @@ -18,6 +18,7 @@ package appeng.items.contents; + import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -39,13 +40,15 @@ import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; + public class PortableCellViewer extends MEMonitorHandler implements IPortableCell { private final ItemStack target; private final IAEItemPowerStorage ips; - public PortableCellViewer(ItemStack is) { + public PortableCellViewer( ItemStack is ) + { super( CellInventory.getCell( is, null ) ); this.ips = (IAEItemPowerStorage) is.getItem(); this.target = is; @@ -58,11 +61,11 @@ public class PortableCellViewer extends MEMonitorHandler implement } @Override - public double extractAEPower(double amt, Actionable mode, PowerMultiplier usePowerMultiplier) + public double extractAEPower( double amt, Actionable mode, PowerMultiplier usePowerMultiplier ) { amt = usePowerMultiplier.multiply( amt ); - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) { return usePowerMultiplier.divide( Math.min( amt, this.ips.getAECurrentPower( this.target ) ) ); } @@ -85,10 +88,11 @@ public class PortableCellViewer extends MEMonitorHandler implement @Override public IConfigManager getConfigManager() { - final ConfigManager out = new ConfigManager( new IConfigManagerHost() { + final ConfigManager out = new ConfigManager( new IConfigManagerHost() + { @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { NBTTagCompound data = Platform.openNbtData( PortableCellViewer.this.target ); manager.writeToNBT( data ); @@ -102,5 +106,4 @@ public class PortableCellViewer extends MEMonitorHandler implement out.readFromNBT( (NBTTagCompound) Platform.openNbtData( this.target ).copy() ); return out; } - } diff --git a/src/main/java/appeng/items/contents/QuartzKnifeObj.java b/src/main/java/appeng/items/contents/QuartzKnifeObj.java index 350da0b3c..5b5b46ac7 100644 --- a/src/main/java/appeng/items/contents/QuartzKnifeObj.java +++ b/src/main/java/appeng/items/contents/QuartzKnifeObj.java @@ -18,16 +18,19 @@ package appeng.items.contents; + import net.minecraft.item.ItemStack; import appeng.api.implementations.guiobjects.IGuiItemObject; + public class QuartzKnifeObj implements IGuiItemObject { final ItemStack is; - public QuartzKnifeObj(ItemStack o) { + public QuartzKnifeObj( ItemStack o ) + { this.is = o; } @@ -36,5 +39,4 @@ public class QuartzKnifeObj implements IGuiItemObject { return this.is; } - } diff --git a/src/main/java/appeng/items/materials/ItemMultiMaterial.java b/src/main/java/appeng/items/materials/ItemMultiMaterial.java index b2a2eb224..e9be02144 100644 --- a/src/main/java/appeng/items/materials/ItemMultiMaterial.java +++ b/src/main/java/appeng/items/materials/ItemMultiMaterial.java @@ -90,37 +90,37 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, super.addCheckedInformation( stack, player, lines, displayAdditionalInformation ); MaterialType mt = this.getTypeByStack( stack ); - if ( mt == null ) + if( mt == null ) return; - if ( mt == MaterialType.NamePress ) + if( mt == MaterialType.NamePress ) { NBTTagCompound c = Platform.openNbtData( stack ); lines.add( c.getString( "InscribeName" ) ); } Upgrades u = this.getType( stack ); - if ( u != null ) + if( u != null ) { List textList = new LinkedList(); - for ( Entry j : u.getSupported().entrySet() ) + for( Entry j : u.getSupported().entrySet() ) { String name = null; int limit = j.getValue(); - if ( j.getKey().getItem() instanceof IItemGroup ) + if( j.getKey().getItem() instanceof IItemGroup ) { IItemGroup ig = (IItemGroup) j.getKey().getItem(); String str = ig.getUnlocalizedGroupName( u.getSupported().keySet(), j.getKey() ); - if ( str != null ) + if( str != null ) name = Platform.gui_localize( str ) + ( limit > 1 ? " (" + limit + ')' : "" ); } - if ( name == null ) + if( name == null ) name = j.getKey().getDisplayName() + ( limit > 1 ? " (" + limit + ')' : "" ); - if ( !textList.contains( name ) ) + if( !textList.contains( name ) ) textList.add( name ); } @@ -133,7 +133,7 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, public MaterialType getTypeByStack( ItemStack is ) { - if ( this.dmgToMaterial.containsKey( is.getItemDamage() ) ) + if( this.dmgToMaterial.containsKey( is.getItemDamage() ) ) return this.dmgToMaterial.get( is.getItemDamage() ); return MaterialType.InvalidType; } @@ -141,7 +141,7 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, @Override public Upgrades getType( ItemStack itemstack ) { - switch ( this.getTypeByStack( itemstack ) ) + switch( this.getTypeByStack( itemstack ) ) { case CardCapacity: return Upgrades.CAPACITY; @@ -162,13 +162,13 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, public IStackSrc createMaterial( MaterialType mat ) { - if ( !mat.isRegistered() ) + if( !mat.isRegistered() ) { boolean enabled = true; - for ( AEFeature f : mat.getFeature() ) + for( AEFeature f : mat.getFeature() ) enabled = enabled && AEConfig.instance.isFeatureEnabled( f ); - if ( enabled ) + if( enabled ) { mat.itemInstance = this; int newMaterialNum = mat.damageValue; @@ -176,7 +176,7 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, mat.stackSrc = new MaterialStackSrc( mat ); - if ( this.dmgToMaterial.get( newMaterialNum ) == null ) + if( this.dmgToMaterial.get( newMaterialNum ) == null ) this.dmgToMaterial.put( newMaterialNum, mat ); else throw new RuntimeException( "Meta Overlap detected." ); @@ -192,25 +192,25 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, public void makeUnique() { - for ( MaterialType mt : ImmutableSet.copyOf( this.dmgToMaterial.values() ) ) + for( MaterialType mt : ImmutableSet.copyOf( this.dmgToMaterial.values() ) ) { - if ( mt.getOreName() != null ) + if( mt.getOreName() != null ) { ItemStack replacement = null; String[] names = mt.getOreName().split( "," ); - for ( String name : names ) + for( String name : names ) { - if ( replacement != null ) + if( replacement != null ) break; List options = OreDictionary.getOres( name ); - if ( options != null && options.size() > 0 ) + if( options != null && options.size() > 0 ) { - for ( ItemStack is : options ) + for( ItemStack is : options ) { - if ( is != null && is.getItem() != null ) + if( is != null && is.getItem() != null ) { replacement = is.copy(); break; @@ -219,15 +219,15 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, } } - if ( replacement == null || AEConfig.instance.useAEVersion( mt ) ) + if( replacement == null || AEConfig.instance.useAEVersion( mt ) ) { // continue using the AE2 item. - for ( String name : names ) + for( String name : names ) OreDictionary.registerOre( name, mt.stack( 1 ) ); } else { - if ( mt.itemInstance == this ) + if( mt.itemInstance == this ) this.dmgToMaterial.remove( mt.damageValue ); mt.itemInstance = replacement.getItem(); @@ -240,7 +240,7 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, @Override public IIcon getIconFromDamage( int dmg ) { - if ( this.dmgToMaterial.containsKey( dmg ) ) + if( this.dmgToMaterial.containsKey( dmg ) ) return this.dmgToMaterial.get( dmg ).IIcon; return new MissingIcon( this ); } @@ -253,11 +253,11 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, private String nameOf( ItemStack is ) { - if ( is == null ) + if( is == null ) return "null"; MaterialType mt = this.getTypeByStack( is ); - if ( mt == null ) + if( mt == null ) return "null"; return this.nameResolver.getName( mt.name() ); @@ -277,9 +277,9 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, } } ); - for ( MaterialType mat : types ) + for( MaterialType mat : types ) { - if ( mat.damageValue >= 0 && mat.isRegistered() && mat.itemInstance == this ) + if( mat.damageValue >= 0 && mat.isRegistered() && mat.itemInstance == this ) cList.add( new ItemStack( this, 1, mat.damageValue ) ); } } @@ -287,12 +287,12 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, @Override public void registerIcons( IIconRegister icoRegister ) { - for ( MaterialType mat : MaterialType.values() ) + for( MaterialType mat : MaterialType.values() ) { - if ( mat.damageValue != -1 ) + if( mat.damageValue != -1 ) { ItemStack what = new ItemStack( this, 1, mat.damageValue ); - if ( this.getTypeByStack( what ) != MaterialType.InvalidType ) + if( this.getTypeByStack( what ) != MaterialType.InvalidType ) { String tex = "appliedenergistics2:" + this.nameOf( what ); mat.IIcon = icoRegister.registerIcon( tex ); @@ -304,31 +304,31 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, @Override public boolean onItemUseFirst( ItemStack is, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { - if ( player.isSneaking() ) + if( player.isSneaking() ) { TileEntity te = world.getTileEntity( x, y, z ); IInventory upgrades = null; - if ( te instanceof IPartHost ) + if( te instanceof IPartHost ) { SelectedPart sp = ( (IPartHost) te ).selectPart( Vec3.createVectorHelper( hitX, hitY, hitZ ) ); - if ( sp.part instanceof IUpgradeableHost ) + if( sp.part instanceof IUpgradeableHost ) upgrades = ( (ISegmentedInventory) sp.part ).getInventoryByName( "upgrades" ); } - else if ( te instanceof IUpgradeableHost ) + else if( te instanceof IUpgradeableHost ) upgrades = ( (ISegmentedInventory) te ).getInventoryByName( "upgrades" ); - if ( upgrades != null && is != null && is.getItem() instanceof IUpgradeModule ) + if( upgrades != null && is != null && is.getItem() instanceof IUpgradeModule ) { IUpgradeModule um = (IUpgradeModule) is.getItem(); Upgrades u = um.getType( is ); - if ( u != null ) + if( u != null ) { InventoryAdaptor ad = InventoryAdaptor.getAdaptor( upgrades, ForgeDirection.UNKNOWN ); - if ( ad != null ) + if( ad != null ) { - if ( player.worldObj.isRemote ) + if( player.worldObj.isRemote ) return false; player.inventory.setInventorySlotContents( player.inventory.currentItem, ad.addItems( is ) ); @@ -357,7 +357,7 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, { eqi = droppedEntity.getConstructor( World.class, double.class, double.class, double.class, ItemStack.class ).newInstance( w, location.posX, location.posY, location.posZ, itemstack ); } - catch ( Throwable t ) + catch( Throwable t ) { throw new RuntimeException( t ); } @@ -366,7 +366,7 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, eqi.motionY = location.motionY; eqi.motionZ = location.motionZ; - if ( location instanceof EntityItem && eqi instanceof EntityItem ) + if( location instanceof EntityItem && eqi instanceof EntityItem ) ( (EntityItem) eqi ).delayBeforeCanPickup = ( (EntityItem) location ).delayBeforeCanPickup; return eqi; @@ -375,7 +375,7 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, @Override public int getBytes( ItemStack is ) { - switch ( this.getTypeByStack( is ) ) + switch( this.getTypeByStack( is ) ) { case Cell1kPart: return KILO; @@ -393,7 +393,7 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, @Override public boolean isStorageComponent( ItemStack is ) { - switch ( this.getTypeByStack( is ) ) + switch( this.getTypeByStack( is ) ) { case Cell1kPart: case Cell4kPart: @@ -421,14 +421,14 @@ public class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, { Matcher a = this.pattern.matcher( o1 ); Matcher b = this.pattern.matcher( o2 ); - if ( a.find() && b.find() ) + if( a.find() && b.find() ) { int ia = Integer.parseInt( a.group( 1 ) ); int ib = Integer.parseInt( b.group( 1 ) ); return Integer.compare( ia, ib ); } } - catch ( Throwable t ) + catch( Throwable t ) { // ek! } diff --git a/src/main/java/appeng/items/materials/MaterialType.java b/src/main/java/appeng/items/materials/MaterialType.java index 0eb06db54..5e847e08b 100644 --- a/src/main/java/appeng/items/materials/MaterialType.java +++ b/src/main/java/appeng/items/materials/MaterialType.java @@ -18,6 +18,7 @@ package appeng.items.materials; + import java.util.EnumSet; import net.minecraft.entity.Entity; @@ -36,82 +37,79 @@ import appeng.entity.EntityChargedQuartz; import appeng.entity.EntityIds; import appeng.entity.EntitySingularity; + public enum MaterialType { - InvalidType(-1, AEFeature.Core), + InvalidType( -1, AEFeature.Core ), - CertusQuartzCrystal(0, AEFeature.Core, "crystalCertusQuartz"), CertusQuartzCrystalCharged(1, AEFeature.Core, EntityChargedQuartz.class), + CertusQuartzCrystal( 0, AEFeature.Core, "crystalCertusQuartz" ), CertusQuartzCrystalCharged( 1, AEFeature.Core, EntityChargedQuartz.class ), - CertusQuartzDust(2, AEFeature.Core, "dustCertusQuartz"), NetherQuartzDust(3, AEFeature.Core, "dustNetherQuartz"), Flour(4, AEFeature.Flour, "dustWheat"), GoldDust( - 51, AEFeature.Core, "dustGold"), IronDust(49, AEFeature.Core, "dustIron"), IronNugget(50, AEFeature.Core, "nuggetIron"), + CertusQuartzDust( 2, AEFeature.Core, "dustCertusQuartz" ), NetherQuartzDust( 3, AEFeature.Core, "dustNetherQuartz" ), Flour( 4, AEFeature.Flour, "dustWheat" ), GoldDust( 51, AEFeature.Core, "dustGold" ), IronDust( 49, AEFeature.Core, "dustIron" ), IronNugget( 50, AEFeature.Core, "nuggetIron" ), - Silicon(5, AEFeature.Core, "itemSilicon"), MatterBall(6), + Silicon( 5, AEFeature.Core, "itemSilicon" ), MatterBall( 6 ), - FluixCrystal(7, AEFeature.Core, "crystalFluix"), FluixDust(8, AEFeature.Core, "dustFluix"), FluixPearl(9, AEFeature.Core, "pearlFluix"), + FluixCrystal( 7, AEFeature.Core, "crystalFluix" ), FluixDust( 8, AEFeature.Core, "dustFluix" ), FluixPearl( 9, AEFeature.Core, "pearlFluix" ), - PurifiedCertusQuartzCrystal(10), PurifiedNetherQuartzCrystal(11), PurifiedFluixCrystal(12), + PurifiedCertusQuartzCrystal( 10 ), PurifiedNetherQuartzCrystal( 11 ), PurifiedFluixCrystal( 12 ), - CalcProcessorPress(13), EngProcessorPress(14), LogicProcessorPress(15), + CalcProcessorPress( 13 ), EngProcessorPress( 14 ), LogicProcessorPress( 15 ), - CalcProcessorPrint(16), EngProcessorPrint(17), LogicProcessorPrint(18), + CalcProcessorPrint( 16 ), EngProcessorPrint( 17 ), LogicProcessorPrint( 18 ), - SiliconPress(19), SiliconPrint(20), + SiliconPress( 19 ), SiliconPrint( 20 ), - NamePress(21), + NamePress( 21 ), - LogicProcessor(22), CalcProcessor(23), EngProcessor(24), + LogicProcessor( 22 ), CalcProcessor( 23 ), EngProcessor( 24 ), // Basic Cards - BasicCard(25), CardRedstone(26), CardCapacity(27), + BasicCard( 25 ), CardRedstone( 26 ), CardCapacity( 27 ), // Adv Cards - AdvCard(28), CardFuzzy(29), CardSpeed(30), CardInverter(31), + AdvCard( 28 ), CardFuzzy( 29 ), CardSpeed( 30 ), CardInverter( 31 ), - Cell2SpatialPart(32, AEFeature.SpatialIO), Cell16SpatialPart(33, AEFeature.SpatialIO), Cell128SpatialPart(34, AEFeature.SpatialIO), + Cell2SpatialPart( 32, AEFeature.SpatialIO ), Cell16SpatialPart( 33, AEFeature.SpatialIO ), Cell128SpatialPart( 34, AEFeature.SpatialIO ), - Cell1kPart(35, AEFeature.StorageCells), Cell4kPart(36, AEFeature.StorageCells), Cell16kPart(37, AEFeature.StorageCells), Cell64kPart(38, - AEFeature.StorageCells), EmptyStorageCell(39, AEFeature.StorageCells), + Cell1kPart( 35, AEFeature.StorageCells ), Cell4kPart( 36, AEFeature.StorageCells ), Cell16kPart( 37, AEFeature.StorageCells ), Cell64kPart( 38, AEFeature.StorageCells ), EmptyStorageCell( 39, AEFeature.StorageCells ), - WoodenGear(40, AEFeature.GrindStone, "gearWood"), + WoodenGear( 40, AEFeature.GrindStone, "gearWood" ), - Wireless(41, AEFeature.WirelessAccessTerminal), WirelessBooster(42, AEFeature.WirelessAccessTerminal), + Wireless( 41, AEFeature.WirelessAccessTerminal ), WirelessBooster( 42, AEFeature.WirelessAccessTerminal ), - FormationCore(43), AnnihilationCore(44), + FormationCore( 43 ), AnnihilationCore( 44 ), - SkyDust(45, AEFeature.Core), + SkyDust( 45, AEFeature.Core ), - EnderDust(46, AEFeature.QuantumNetworkBridge, "dustEnder,dustEnderPearl", EntitySingularity.class), Singularity(47, AEFeature.QuantumNetworkBridge, - EntitySingularity.class), QESingularity(48, AEFeature.QuantumNetworkBridge, EntitySingularity.class), + EnderDust( 46, AEFeature.QuantumNetworkBridge, "dustEnder,dustEnderPearl", EntitySingularity.class ), Singularity( 47, AEFeature.QuantumNetworkBridge, EntitySingularity.class ), QESingularity( 48, AEFeature.QuantumNetworkBridge, EntitySingularity.class ), - BlankPattern(52), CardCrafting(53); + BlankPattern( 52 ), CardCrafting( 53 ); - private String oreName; private final EnumSet features; - private Class droppedEntity; - // IIcon for the material. - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public IIcon IIcon; - public Item itemInstance; public int damageValue; - - private boolean isRegistered = false; - // stack! public MaterialStackSrc stackSrc; + private String oreName; + private Class droppedEntity; + private boolean isRegistered = false; - MaterialType(int metaValue) { + MaterialType( int metaValue ) + { this.damageValue = metaValue; this.features = EnumSet.of( AEFeature.Core ); } - MaterialType(int metaValue, AEFeature part) { + MaterialType( int metaValue, AEFeature part ) + { this.damageValue = metaValue; this.features = EnumSet.of( part ); } - MaterialType(int metaValue, AEFeature part, Class c) { + MaterialType( int metaValue, AEFeature part, Class c ) + { this.features = EnumSet.of( part ); this.damageValue = metaValue; this.droppedEntity = c; @@ -119,7 +117,8 @@ public enum MaterialType EntityRegistry.registerModEntity( this.droppedEntity, this.droppedEntity.getSimpleName(), EntityIds.get( this.droppedEntity ), AppEng.instance, 16, 4, true ); } - MaterialType(int metaValue, AEFeature part, String oreDictionary, Class c) { + MaterialType( int metaValue, AEFeature part, String oreDictionary, Class c ) + { this.features = EnumSet.of( part ); this.damageValue = metaValue; this.oreName = oreDictionary; @@ -127,13 +126,14 @@ public enum MaterialType EntityRegistry.registerModEntity( this.droppedEntity, this.droppedEntity.getSimpleName(), EntityIds.get( this.droppedEntity ), AppEng.instance, 16, 4, true ); } - MaterialType(int metaValue, AEFeature part, String oreDictionary) { + MaterialType( int metaValue, AEFeature part, String oreDictionary ) + { this.features = EnumSet.of( part ); this.damageValue = metaValue; this.oreName = oreDictionary; } - public ItemStack stack(int size) + public ItemStack stack( int size ) { return new ItemStack( this.itemInstance, size, this.damageValue ); } diff --git a/src/main/java/appeng/items/misc/ItemCrystalSeed.java b/src/main/java/appeng/items/misc/ItemCrystalSeed.java index 2c26a90de..3b489afd6 100644 --- a/src/main/java/appeng/items/misc/ItemCrystalSeed.java +++ b/src/main/java/appeng/items/misc/ItemCrystalSeed.java @@ -80,7 +80,7 @@ public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal { ResolverResult resolver = null; - for ( ItemStack crystalSeedStack : AEApi.instance().definitions().items().crystalSeed().maybeStack( 1 ).asSet() ) + for( ItemStack crystalSeedStack : AEApi.instance().definitions().items().crystalSeed().maybeStack( 1 ).asSet() ) { crystalSeedStack.setItemDamage( certus2 ); crystalSeedStack = newStyle( crystalSeedStack ); @@ -98,7 +98,7 @@ public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal private int getProgress( ItemStack is ) { - if ( is.hasTagCompound() ) + if( is.hasTagCompound() ) { return is.getTagCompound().getInteger( "progress" ); } @@ -120,28 +120,28 @@ public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal final IMaterials materials = AEApi.instance().definitions().materials(); final int size = is.stackSize; - if ( newDamage == Certus + SINGLE_OFFSET ) + if( newDamage == Certus + SINGLE_OFFSET ) { - for ( ItemStack quartzStack : materials.purifiedCertusQuartzCrystal().maybeStack( size ).asSet() ) + for( ItemStack quartzStack : materials.purifiedCertusQuartzCrystal().maybeStack( size ).asSet() ) { return quartzStack; } } - if ( newDamage == Nether + SINGLE_OFFSET ) + if( newDamage == Nether + SINGLE_OFFSET ) { - for ( ItemStack quartzStack : materials.purifiedNetherQuartzCrystal().maybeStack( size ).asSet() ) + for( ItemStack quartzStack : materials.purifiedNetherQuartzCrystal().maybeStack( size ).asSet() ) { return quartzStack; } } - if ( newDamage == Fluix + SINGLE_OFFSET ) + if( newDamage == Fluix + SINGLE_OFFSET ) { - for ( ItemStack quartzStack : materials.purifiedFluixCrystal().maybeStack( size ).asSet() ) + for( ItemStack quartzStack : materials.purifiedFluixCrystal().maybeStack( size ).asSet() ) { return quartzStack; } } - if ( newDamage > END ) + if( newDamage > END ) return null; this.setProgress( is, newDamage ); @@ -153,10 +153,6 @@ public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal NBTTagCompound comp = Platform.openNbtData( is ); comp.setInteger( "progress", newDamage ); is.setItemDamage( is.getItemDamage() / LEVEL_OFFSET * LEVEL_OFFSET ); - } @Override - public int getEntityLifespan( ItemStack itemStack, World world ) - { - return Integer.MAX_VALUE; } @Override @@ -173,25 +169,31 @@ public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal lines.add( Math.floor( (float) progress / (float) ( SINGLE_OFFSET / 100 ) ) + "%" ); super.addCheckedInformation( stack, player, lines, displayAdditionalInformation ); - } @Override + } + + @Override + public int getEntityLifespan( ItemStack itemStack, World world ) + { + return Integer.MAX_VALUE; + } + + @Override public String getUnlocalizedName( ItemStack is ) { int damage = this.getProgress( is ); - if ( damage < Certus + SINGLE_OFFSET ) + if( damage < Certus + SINGLE_OFFSET ) return this.getUnlocalizedName() + ".Certus"; - if ( damage < Nether + SINGLE_OFFSET ) + if( damage < Nether + SINGLE_OFFSET ) return this.getUnlocalizedName() + ".Nether"; - if ( damage < Fluix + SINGLE_OFFSET ) + if( damage < Fluix + SINGLE_OFFSET ) return this.getUnlocalizedName() + ".Fluix"; return this.getUnlocalizedName(); } - - @Override public boolean isDamageable() { @@ -223,27 +225,27 @@ public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal int damage = this.getProgress( stack ); - if ( damage < Certus + SINGLE_OFFSET ) + if( damage < Certus + SINGLE_OFFSET ) list = this.certus; - else if ( damage < Nether + SINGLE_OFFSET ) + else if( damage < Nether + SINGLE_OFFSET ) { damage -= Nether; list = this.nether; } - else if ( damage < Fluix + SINGLE_OFFSET ) + else if( damage < Fluix + SINGLE_OFFSET ) { damage -= Fluix; list = this.fluix; } - if ( list == null ) + if( list == null ) return Items.diamond.getIconFromDamage( 0 ); - if ( damage < LEVEL_OFFSET ) + if( damage < LEVEL_OFFSET ) return list[0]; - else if ( damage < LEVEL_OFFSET * 2 ) + else if( damage < LEVEL_OFFSET * 2 ) return list[1]; else return list[2]; @@ -282,7 +284,7 @@ public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal egc.motionY = location.motionY; egc.motionZ = location.motionZ; - if ( location instanceof EntityItem ) + if( location instanceof EntityItem ) egc.delayBeforeCanPickup = ( (EntityItem) location ).delayBeforeCanPickup; return egc; @@ -306,6 +308,4 @@ public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal l.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + Nether ) ) ); l.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + Fluix ) ) ); } - - } diff --git a/src/main/java/appeng/items/misc/ItemEncodedPattern.java b/src/main/java/appeng/items/misc/ItemEncodedPattern.java index cf53961eb..a5dfb6efb 100644 --- a/src/main/java/appeng/items/misc/ItemEncodedPattern.java +++ b/src/main/java/appeng/items/misc/ItemEncodedPattern.java @@ -53,7 +53,7 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt { this.setFeature( EnumSet.of( AEFeature.Patterns ) ); this.setMaxStackSize( 1 ); - if ( Platform.isClient() ) + if( Platform.isClient() ) MinecraftForgeClient.registerItemRenderer( this, new ItemEncodedPatternRenderer() ); } @@ -73,18 +73,18 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt private boolean clearPattern( ItemStack stack, EntityPlayer player ) { - if ( player.isSneaking() ) + if( player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return false; InventoryPlayer inv = player.inventory; - for ( int s = 0; s < player.inventory.getSizeInventory(); s++ ) + for( int s = 0; s < player.inventory.getSizeInventory(); s++ ) { - if ( inv.getStackInSlot( s ) == stack ) + if( inv.getStackInSlot( s ) == stack ) { - for ( ItemStack blankPattern : AEApi.instance().definitions().materials().blankPattern().maybeStack( stack.stackSize ).asSet() ) + for( ItemStack blankPattern : AEApi.instance().definitions().materials().blankPattern().maybeStack( stack.stackSize ).asSet() ) { inv.setInventorySlotContents( s, blankPattern ); } @@ -102,7 +102,7 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt { ICraftingPatternDetails details = this.getPatternForItem( stack, player.worldObj ); - if ( details == null ) + if( details == null ) { lines.add( EnumChatFormatting.RED + GuiText.InvalidPattern.getLocal() ); return; @@ -118,9 +118,9 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt String with = GuiText.With.getLocal() + ": "; boolean first = true; - for ( IAEItemStack anOut : out ) + for( IAEItemStack anOut : out ) { - if ( anOut == null ) + if( anOut == null ) { continue; } @@ -130,9 +130,9 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt } first = true; - for ( IAEItemStack anIn : in ) + for( IAEItemStack anIn : in ) { - if ( anIn == null ) + if( anIn == null ) { continue; } @@ -149,7 +149,7 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt { return new PatternHelper( is, w ); } - catch ( Throwable t ) + catch( Throwable t ) { return null; } @@ -158,16 +158,16 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt public ItemStack getOutput( ItemStack item ) { ItemStack out = SIMPLE_CACHE.get( item ); - if ( out != null ) + if( out != null ) return out; World w = CommonHelper.proxy.getWorld(); - if ( w == null ) + if( w == null ) return null; ICraftingPatternDetails details = this.getPatternForItem( item, w ); - if ( details == null ) + if( details == null ) return null; SIMPLE_CACHE.put( item, out = details.getCondensedOutputs()[0].getItemStack() ); diff --git a/src/main/java/appeng/items/misc/ItemPaintBall.java b/src/main/java/appeng/items/misc/ItemPaintBall.java index 8d715484b..6c2ecf95b 100644 --- a/src/main/java/appeng/items/misc/ItemPaintBall.java +++ b/src/main/java/appeng/items/misc/ItemPaintBall.java @@ -45,7 +45,7 @@ public class ItemPaintBall extends AEBaseItem this.setFeature( EnumSet.of( AEFeature.PaintBalls ) ); this.setHasSubtypes( true ); - if ( Platform.isClient() ) + if( Platform.isClient() ) MinecraftForgeClient.registerItemRenderer( this, new PaintBallRender() ); } @@ -63,10 +63,10 @@ public class ItemPaintBall extends AEBaseItem public AEColor getColor( ItemStack is ) { int dmg = is.getItemDamage(); - if ( dmg >= DAMAGE_THRESHOLD ) + if( dmg >= DAMAGE_THRESHOLD ) dmg -= DAMAGE_THRESHOLD; - if ( dmg >= AEColor.values().length ) + if( dmg >= AEColor.values().length ) return AEColor.Transparent; return AEColor.values()[dmg]; @@ -75,12 +75,12 @@ public class ItemPaintBall extends AEBaseItem @Override public void getSubItems( Item i, CreativeTabs ct, List l ) { - for ( AEColor c : AEColor.values() ) - if ( c != AEColor.Transparent ) + for( AEColor c : AEColor.values() ) + if( c != AEColor.Transparent ) l.add( new ItemStack( this, 1, c.ordinal() ) ); - for ( AEColor c : AEColor.values() ) - if ( c != AEColor.Transparent ) + for( AEColor c : AEColor.values() ) + if( c != AEColor.Transparent ) l.add( new ItemStack( this, 1, DAMAGE_THRESHOLD + c.ordinal() ) ); } diff --git a/src/main/java/appeng/items/parts/ItemFacade.java b/src/main/java/appeng/items/parts/ItemFacade.java index e6f35f1ae..0a0a66e1a 100644 --- a/src/main/java/appeng/items/parts/ItemFacade.java +++ b/src/main/java/appeng/items/parts/ItemFacade.java @@ -64,7 +64,7 @@ public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassIte { this.setFeature( EnumSet.of( AEFeature.Facades ) ); this.setHasSubtypes( true ); - if ( Platform.isClient() ) + if( Platform.isClient() ) MinecraftForgeClient.registerItemRenderer( this, BusRenderer.INSTANCE ); } @@ -87,12 +87,12 @@ public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassIte try { ItemStack in = this.getTextureItem( is ); - if ( in != null ) + if( in != null ) { return super.getItemStackDisplayName( is ) + " - " + in.getDisplayName(); } } - catch ( Throwable ignored ) + catch( Throwable ignored ) { } @@ -107,69 +107,12 @@ public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassIte list.addAll( this.subTypes ); } - @Override - public FacadePart createPartFromItemStack( ItemStack is, ForgeDirection side ) - { - ItemStack in = this.getTextureItem( is ); - if ( in != null ) - return new FacadePart( is, side ); - return null; - } - - @Override - public ItemStack getTextureItem( ItemStack is ) - { - Block blk = this.getBlock( is ); - if ( blk != null ) - return new ItemStack( blk, 1, this.getMeta( is ) ); - return null; - } - - @Override - public int getMeta( ItemStack is ) - { - NBTTagCompound data = is.getTagCompound(); - if ( data != null ) - { - int[] blk = data.getIntArray( "x" ); - if ( blk != null && blk.length == 2 ) - return blk[1]; - } - return 0; - } - - @Override - public Block getBlock( ItemStack is ) - { - NBTTagCompound data = is.getTagCompound(); - if ( data != null ) - { - if ( data.hasKey( "modid" ) && data.hasKey( "itemname" ) ) - { - return GameRegistry.findBlock( data.getString( "modid" ), data.getString( "itemname" ) ); - } - else - { - int[] blk = data.getIntArray( "x" ); - if ( blk != null && blk.length == 2 ) - return Block.getBlockById( blk[0] ); - } - } - return Blocks.glass; - } - - public List getFacades() - { - this.calculateSubTypes(); - return this.subTypes; - } - private void calculateSubTypes() { - if ( this.subTypes == null ) + if( this.subTypes == null ) { this.subTypes = new ArrayList(); - for ( Object blk : Block.blockRegistry ) + for( Object blk : Block.blockRegistry ) { Block b = (Block) blk; try @@ -178,31 +121,31 @@ public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassIte List tmpList = new ArrayList(); b.getSubBlocks( item, b.getCreativeTabToDisplayOn(), tmpList ); - for ( ItemStack l : tmpList ) + for( ItemStack l : tmpList ) { ItemStack facade = this.createFacadeForItem( l, false ); - if ( facade != null ) + if( facade != null ) this.subTypes.add( facade ); } } - catch ( Throwable t ) + catch( Throwable t ) { // just absorb.. } } - if ( FacadeConfig.instance.hasChanged() ) + if( FacadeConfig.instance.hasChanged() ) FacadeConfig.instance.save(); } } public ItemStack createFacadeForItem( ItemStack l, boolean returnItem ) { - if ( l == null ) + if( l == null ) return null; Block b = Block.getBlockFromItem( l.getItem() ); - if ( b == null || l.hasTagCompound() ) + if( b == null || l.hasTagCompound() ) return null; int metadata = l.getItem().getMetadata( l.getItemDamage() ); @@ -212,9 +155,9 @@ public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassIte boolean disableOre = b instanceof OreQuartz; boolean defaultValue = ( b.isOpaqueCube() && !b.getTickRandomly() && !hasTile && !disableOre ) || enableGlass; - if ( FacadeConfig.instance.checkEnabled( b, metadata, defaultValue ) ) + if( FacadeConfig.instance.checkEnabled( b, metadata, defaultValue ) ) { - if ( returnItem ) + if( returnItem ) return l; ItemStack is = new ItemStack( this ); @@ -232,17 +175,74 @@ public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassIte return null; } + @Override + public FacadePart createPartFromItemStack( ItemStack is, ForgeDirection side ) + { + ItemStack in = this.getTextureItem( is ); + if( in != null ) + return new FacadePart( is, side ); + return null; + } + + @Override + public ItemStack getTextureItem( ItemStack is ) + { + Block blk = this.getBlock( is ); + if( blk != null ) + return new ItemStack( blk, 1, this.getMeta( is ) ); + return null; + } + + @Override + public int getMeta( ItemStack is ) + { + NBTTagCompound data = is.getTagCompound(); + if( data != null ) + { + int[] blk = data.getIntArray( "x" ); + if( blk != null && blk.length == 2 ) + return blk[1]; + } + return 0; + } + + @Override + public Block getBlock( ItemStack is ) + { + NBTTagCompound data = is.getTagCompound(); + if( data != null ) + { + if( data.hasKey( "modid" ) && data.hasKey( "itemname" ) ) + { + return GameRegistry.findBlock( data.getString( "modid" ), data.getString( "itemname" ) ); + } + else + { + int[] blk = data.getIntArray( "x" ); + if( blk != null && blk.length == 2 ) + return Block.getBlockById( blk[0] ); + } + } + return Blocks.glass; + } + + public List getFacades() + { + this.calculateSubTypes(); + return this.subTypes; + } + public ItemStack getCreativeTabIcon() { this.calculateSubTypes(); - if ( this.subTypes.isEmpty() ) + if( this.subTypes.isEmpty() ) return new ItemStack( Items.cake ); return this.subTypes.get( 0 ); } public ItemStack createFromIDs( int[] ids ) { - for ( ItemStack facadeStack : AEApi.instance().definitions().items().facade().maybeStack( 1 ).asSet() ) + for( ItemStack facadeStack : AEApi.instance().definitions().items().facade().maybeStack( 1 ).asSet() ) { NBTTagCompound facadeTag = new NBTTagCompound(); facadeTag.setIntArray( "x", ids.clone() ); @@ -259,11 +259,11 @@ public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassIte { ItemStack out = this.getTextureItem( is ); - if ( out == null || out.getItem() == null ) + if( out == null || out.getItem() == null ) return false; Block blk = Block.getBlockFromItem( out.getItem() ); - if ( blk != null && blk.canRenderInPass( 1 ) ) + if( blk != null && blk.canRenderInPass( 1 ) ) return true; return false; diff --git a/src/main/java/appeng/items/parts/ItemMultiPart.java b/src/main/java/appeng/items/parts/ItemMultiPart.java index 109e1c2f7..d7cbb3b3d 100644 --- a/src/main/java/appeng/items/parts/ItemMultiPart.java +++ b/src/main/java/appeng/items/parts/ItemMultiPart.java @@ -18,6 +18,7 @@ package appeng.items.parts; + import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -27,7 +28,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import javax.annotation.Nullable; import net.minecraft.client.renderer.texture.IIconRegister; @@ -50,29 +50,20 @@ import appeng.api.util.AEColor; import appeng.core.AEConfig; import appeng.core.AELog; import appeng.core.features.AEFeature; -import appeng.core.features.NameResolver; import appeng.core.features.ItemStackSrc; +import appeng.core.features.NameResolver; import appeng.core.localization.GuiText; import appeng.items.AEBaseItem; + public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup { + public static ItemMultiPart instance; private final NameResolver nameResolver; - - private static class PartTypeIst - { - private PartType part; - private int variant; - - @SideOnly(Side.CLIENT) - private IIcon ico; - } - private final Map dmgToPart = new HashMap(); - public static ItemMultiPart instance; - - public ItemMultiPart( IPartHelper partHelper ) { + public ItemMultiPart( IPartHelper partHelper ) + { this.nameResolver = new NameResolver( this.getClass() ); this.setFeature( EnumSet.of( AEFeature.Core ) ); partHelper.setItemBusRenderer( this ); @@ -85,26 +76,26 @@ public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup int varID = 0; // verify - for (PartTypeIst p : this.dmgToPart.values()) + for( PartTypeIst p : this.dmgToPart.values() ) { - if ( p.part == mat && p.variant == varID ) + if( p.part == mat && p.variant == varID ) throw new RuntimeException( "Cannot create the same material twice..." ); } boolean enabled = true; - for (AEFeature f : mat.getFeature()) + for( AEFeature f : mat.getFeature() ) enabled = enabled && AEConfig.instance.isFeatureEnabled( f ); int newPartNum = mat.baseDamage + varID; ItemStackSrc output = new ItemStackSrc( this, newPartNum ); - if ( enabled ) + if( enabled ) { PartTypeIst pti = new PartTypeIst(); pti.part = mat; pti.variant = varID; - if ( this.dmgToPart.get( newPartNum ) == null ) + if( this.dmgToPart.get( newPartNum ) == null ) { this.dmgToPart.put( newPartNum, pti ); return output; @@ -118,7 +109,7 @@ public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup return output; } - public ItemStackSrc createPart(PartType mat, Enum variant) + public ItemStackSrc createPart( PartType mat, Enum variant ) { try { @@ -126,7 +117,7 @@ public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup ItemStack is = new ItemStack( this ); mat.getPart().getConstructor( ItemStack.class ).newInstance( is ); } - catch (Throwable e) + catch( Throwable e ) { AELog.integration( e ); e.printStackTrace(); @@ -136,17 +127,17 @@ public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup int varID = variant == null ? 0 : variant.ordinal(); // verify - for (PartTypeIst p : this.dmgToPart.values()) + for( PartTypeIst p : this.dmgToPart.values() ) { - if ( p.part == mat && p.variant == varID ) + if( p.part == mat && p.variant == varID ) throw new RuntimeException( "Cannot create the same material twice..." ); } boolean enabled = true; - for (AEFeature f : mat.getFeature()) + for( AEFeature f : mat.getFeature() ) enabled = enabled && AEConfig.instance.isFeatureEnabled( f ); - if ( enabled ) + if( enabled ) { int newPartNum = mat.baseDamage + varID; ItemStackSrc output = new ItemStackSrc( this, newPartNum ); @@ -155,7 +146,7 @@ public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup pti.part = mat; pti.variant = varID; - if ( this.dmgToPart.get( newPartNum ) == null ) + if( this.dmgToPart.get( newPartNum ) == null ) { this.dmgToPart.put( newPartNum, pti ); return output; @@ -167,77 +158,101 @@ public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup return null; } - public int getDamageByType(PartType t) + public int getDamageByType( PartType t ) { - for (Entry pt : this.dmgToPart.entrySet()) + for( Entry pt : this.dmgToPart.entrySet() ) { - if ( pt.getValue().part == t ) + if( pt.getValue().part == t ) return pt.getKey(); } return -1; } - @Nullable - public PartType getTypeByStack(ItemStack is) - { - if ( is == null ) - return null; - - PartTypeIst pt = this.dmgToPart.get( is.getItemDamage() ); - if ( pt != null ) - return pt.part; - - return null; - } - @Override - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public int getSpriteNumber() { return 0; } @Override - public IIcon getIconFromDamage(int dmg) + public IIcon getIconFromDamage( int dmg ) { return this.dmgToPart.get( dmg ).ico; } @Override - public String getUnlocalizedName(ItemStack is) + public boolean onItemUse( ItemStack is, EntityPlayer player, World w, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) + { + return AEApi.instance().partHelper().placeBus( is, x, y, z, side, player, w ); + } + + @Override + public String getUnlocalizedName( ItemStack is ) { return "item.appliedenergistics2." + this.getName( is ); } - public String getName(ItemStack is) + public String getName( ItemStack is ) { return this.nameResolver.getName( this.getTypeByStack( is ).name() ); } + @Nullable + public PartType getTypeByStack( ItemStack is ) + { + if( is == null ) + return null; + + PartTypeIst pt = this.dmgToPart.get( is.getItemDamage() ); + if( pt != null ) + return pt.part; + + return null; + } + @Override - public String getItemStackDisplayName(ItemStack is) + public String getItemStackDisplayName( ItemStack is ) { PartType pt = this.getTypeByStack( is ); - if ( pt == null ) + if( pt == null ) return "Unnamed"; - if ( pt.isCable() ) + if( pt.isCable() ) { final AEColor[] variants = AEColor.values(); return super.getItemStackDisplayName( is ) + " - " + variants[this.dmgToPart.get( is.getItemDamage() ).variant].toString(); } - if ( pt.getExtraName() != null ) + if( pt.getExtraName() != null ) return super.getItemStackDisplayName( is ) + " - " + pt.getExtraName().getLocal(); return super.getItemStackDisplayName( is ); } @Override - public void registerIcons(IIconRegister par1IconRegister) + public void getSubItems( Item number, CreativeTabs tab, List cList ) { - for (Entry part : this.dmgToPart.entrySet()) + List> types = new ArrayList>( this.dmgToPart.entrySet() ); + Collections.sort( types, new Comparator>() + { + + @Override + public int compare( Entry o1, Entry o2 ) + { + return o1.getValue().part.name().compareTo( o2.getValue().part.name() ); + } + } ); + + for( Entry part : types ) + cList.add( new ItemStack( this, 1, part.getKey() ) ); + } + + @Override + public void registerIcons( IIconRegister par1IconRegister ) + { + for( Entry part : this.dmgToPart.entrySet() ) { String tex = "appliedenergistics2:" + this.getName( new ItemStack( this, 1, part.getKey() ) ); part.getValue().ico = par1IconRegister.registerIcon( tex ); @@ -245,60 +260,35 @@ public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup } @Override - public boolean onItemUse(ItemStack is, EntityPlayer player, World w, int x, int y, int z, int side, float hitX, float hitY, float hitZ) - { - return AEApi.instance().partHelper().placeBus( is, x, y, z, side, player, w ); - } - - @Override - public IPart createPartFromItemStack(ItemStack is) + public IPart createPartFromItemStack( ItemStack is ) { try { PartType t = this.getTypeByStack( is ); - if ( t != null ) + if( t != null ) { - if ( t.constructor == null ) + if( t.constructor == null ) t.constructor = t.getPart().getConstructor( ItemStack.class ); return t.constructor.newInstance( is ); } } - catch (Throwable e) + catch( Throwable e ) { - throw new RuntimeException( "Unable to construct IBusPart from IBusItem : " + this.getTypeByStack( is ).getPart().getName() - + " ; Possibly didn't have correct constructor( ItemStack )", e ); + throw new RuntimeException( "Unable to construct IBusPart from IBusItem : " + this.getTypeByStack( is ).getPart().getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); } return null; } - @Override - public void getSubItems(Item number, CreativeTabs tab, List cList) + public int variantOf( int itemDamage ) { - List> types = new ArrayList>( this.dmgToPart.entrySet() ); - Collections.sort( types, new Comparator>() { - - @Override - public int compare(Entry o1, Entry o2) - { - return o1.getValue().part.name().compareTo( o2.getValue().part.name() ); - } - - } ); - - for (Entry part : types) - cList.add( new ItemStack( this, 1, part.getKey() ) ); - } - - public int variantOf(int itemDamage) - { - if ( this.dmgToPart.containsKey( itemDamage ) ) + if( this.dmgToPart.containsKey( itemDamage ) ) return this.dmgToPart.get( itemDamage ).variant; return 0; } @Override - public String getUnlocalizedGroupName(Set others, ItemStack is) + public String getUnlocalizedGroupName( Set others, ItemStack is ) { boolean importBus = false; boolean exportBus = false; @@ -306,36 +296,45 @@ public class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup PartType u = this.getTypeByStack( is ); - for (ItemStack stack : others) + for( ItemStack stack : others ) { - if ( stack.getItem() == this ) + if( stack.getItem() == this ) { PartType pt = this.getTypeByStack( stack ); - switch (pt) + switch( pt ) { - case ImportBus: - importBus = true; - if ( u == pt ) - group = true; - break; - case ExportBus: - exportBus = true; - if ( u == pt ) - group = true; - break; - default: + case ImportBus: + importBus = true; + if( u == pt ) + group = true; + break; + case ExportBus: + exportBus = true; + if( u == pt ) + group = true; + break; + default: } } } - if ( group && importBus && exportBus ) + if( group && importBus && exportBus ) return GuiText.IOBuses.getUnlocalized(); return null; } - public ItemStack getStackFromTypeAndVariant(PartType mt, int variant) + public ItemStack getStackFromTypeAndVariant( PartType mt, int variant ) { return new ItemStack( this, 1, mt.baseDamage + variant ); } + + private static class PartTypeIst + { + private PartType part; + private int variant; + + @SideOnly( Side.CLIENT ) + private IIcon ico; + } } diff --git a/src/main/java/appeng/items/parts/PartType.java b/src/main/java/appeng/items/parts/PartType.java index 236ba93d3..d87c57457 100644 --- a/src/main/java/appeng/items/parts/PartType.java +++ b/src/main/java/appeng/items/parts/PartType.java @@ -152,11 +152,10 @@ public enum PartType InterfaceTerminal( 480, EnumSet.of( AEFeature.InterfaceTerminal ), PartInterfaceTerminal.class ); + public final int baseDamage; private final EnumSet features; private final Class myPart; private final GuiText extraName; - public final int baseDamage; - public Constructor constructor; PartType( int baseMetaValue, EnumSet features, Class c ) diff --git a/src/main/java/appeng/items/storage/ItemBasicStorageCell.java b/src/main/java/appeng/items/storage/ItemBasicStorageCell.java index ea026dcf5..5f8dfa4ed 100644 --- a/src/main/java/appeng/items/storage/ItemBasicStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemBasicStorageCell.java @@ -71,7 +71,7 @@ public class ItemBasicStorageCell extends AEBaseItem implements IStorageCell, II this.totalBytes = kilobytes * 1024; this.component = whichCell; - switch ( this.component ) + switch( this.component ) { case Cell1kPart: this.idleDrain = 0.5; @@ -100,31 +100,25 @@ public class ItemBasicStorageCell extends AEBaseItem implements IStorageCell, II { IMEInventoryHandler inventory = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - if ( inventory instanceof ICellInventoryHandler ) + if( inventory instanceof ICellInventoryHandler ) { - ICellInventoryHandler handler = ( ICellInventoryHandler ) inventory; + ICellInventoryHandler handler = (ICellInventoryHandler) inventory; ICellInventory cellInventory = handler.getCellInv(); - if ( cellInventory != null ) + if( cellInventory != null ) { - lines.add( cellInventory.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' - + cellInventory.getTotalBytes() + ' ' - + GuiText.BytesUsed.getLocal() ); + lines.add( cellInventory.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); - lines.add( cellInventory.getStoredItemTypes() + " " + GuiText.Of.getLocal() - + ' ' + cellInventory.getTotalItemTypes() + ' ' - + GuiText.Types.getLocal() ); + lines.add( cellInventory.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); - if ( handler.isPreformatted() ) + if( handler.isPreformatted() ) { - String List = ( handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST ? GuiText.Included - : GuiText.Excluded ).getLocal(); + String List = ( handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST ? GuiText.Included : GuiText.Excluded ).getLocal(); - if ( handler.isFuzzy() ) + if( handler.isFuzzy() ) lines.add( GuiText.Partitioned.getLocal() + " - " + List + ' ' + GuiText.Fuzzy.getLocal() ); else lines.add( GuiText.Partitioned.getLocal() + " - " + List + ' ' + GuiText.Precise.getLocal() ); - } } } @@ -204,7 +198,7 @@ public class ItemBasicStorageCell extends AEBaseItem implements IStorageCell, II { return FuzzyMode.valueOf( fz ); } - catch ( Throwable t ) + catch( Throwable t ) { return FuzzyMode.IGNORE_ALL; } @@ -225,35 +219,35 @@ public class ItemBasicStorageCell extends AEBaseItem implements IStorageCell, II private boolean disassembleDrive( ItemStack stack, World world, EntityPlayer player ) { - if ( player.isSneaking() ) + if( player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return false; InventoryPlayer playerInventory = player.inventory; IMEInventoryHandler inv = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - if ( inv != null && playerInventory.getCurrentItem() == stack ) + if( inv != null && playerInventory.getCurrentItem() == stack ) { InventoryAdaptor ia = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); IItemList list = inv.getAvailableItems( StorageChannel.ITEMS.createList() ); - if ( list.isEmpty() && ia != null ) + if( list.isEmpty() && ia != null ) { playerInventory.setInventorySlotContents( playerInventory.currentItem, null ); ItemStack extraB = ia.addItems( this.component.stack( 1 ) ); - if ( extraB != null ) + if( extraB != null ) player.dropPlayerItemWithRandomChoice( extraB, false ); - for ( ItemStack storageCellStack : AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).asSet() ) + for( ItemStack storageCellStack : AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).asSet() ) { final ItemStack extraA = ia.addItems( storageCellStack ); - if ( extraA != null ) + if( extraA != null ) { player.dropPlayerItemWithRandomChoice( extraA, false ); } } - if ( player.inventoryContainer != null ) + if( player.inventoryContainer != null ) player.inventoryContainer.detectAndSendChanges(); return true; @@ -272,7 +266,7 @@ public class ItemBasicStorageCell extends AEBaseItem implements IStorageCell, II @Override public ItemStack getContainerItem( ItemStack itemStack ) { - for ( ItemStack stack : AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).asSet() ) + for( ItemStack stack : AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).asSet() ) { return stack; } diff --git a/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java b/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java index 7bfecc16c..9c5cd3239 100644 --- a/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java @@ -58,7 +58,7 @@ public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorag public void addCheckedInformation( ItemStack stack, EntityPlayer player, List lines, boolean displayAdditionalInformation ) { WorldCoord wc = this.getStoredSize( stack ); - if ( wc.x > 0 ) + if( wc.x > 0 ) lines.add( GuiText.StoredSize.getLocal() + ": " + wc.x + " x " + wc.y + " x " + wc.z ); } @@ -77,20 +77,20 @@ public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorag @Override public World getWorld( ItemStack is ) { - if ( is.hasTagCompound() ) + if( is.hasTagCompound() ) { NBTTagCompound c = is.getTagCompound(); int dim = c.getInteger( "StorageDim" ); World w = DimensionManager.getWorld( dim ); - if ( w == null ) + if( w == null ) { DimensionManager.initDimension( dim ); w = DimensionManager.getWorld( dim ); } - if ( w != null ) + if( w != null ) { - if ( w.provider instanceof StorageWorldProvider ) + if( w.provider instanceof StorageWorldProvider ) { return w; } @@ -102,10 +102,10 @@ public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorag @Override public WorldCoord getStoredSize( ItemStack is ) { - if ( is.hasTagCompound() ) + if( is.hasTagCompound() ) { NBTTagCompound c = is.getTagCompound(); - if ( Platform.isServer() ) + if( Platform.isServer() ) { int dim = c.getInteger( "StorageDim" ); return WorldSettings.getInstance().getStoredSize( dim ); @@ -120,10 +120,10 @@ public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorag public WorldCoord getMin( ItemStack is ) { World w = this.getWorld( is ); - if ( w != null ) + if( w != null ) { - NBTTagCompound info = ( NBTTagCompound ) w.getWorldInfo().getAdditionalProperty( "storageCell" ); - if ( info != null ) + NBTTagCompound info = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty( "storageCell" ); + if( info != null ) { return new WorldCoord( info.getInteger( "minX" ), info.getInteger( "minY" ), info.getInteger( "minZ" ) ); } @@ -135,10 +135,10 @@ public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorag public WorldCoord getMax( ItemStack is ) { World w = this.getWorld( is ); - if ( w != null ) + if( w != null ) { - NBTTagCompound info = ( NBTTagCompound ) w.getWorldInfo().getAdditionalProperty( "storageCell" ); - if ( info != null ) + NBTTagCompound info = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty( "storageCell" ); + if( info != null ) { return new WorldCoord( info.getInteger( "maxX" ), info.getInteger( "maxY" ), info.getInteger( "maxZ" ) ); } @@ -159,15 +159,14 @@ public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorag int floorBuffer = 64; World destination = this.getWorld( is ); - if ( ( scale.x == 0 && scale.y == 0 && scale.z == 0 ) || ( scale.x == targetX && scale.y == targetY && scale.z == targetZ ) ) + if( ( scale.x == 0 && scale.y == 0 && scale.z == 0 ) || ( scale.x == targetX && scale.y == targetY && scale.z == targetZ ) ) { - if ( targetX <= maxSize && targetY <= maxSize && targetZ <= maxSize ) + if( targetX <= maxSize && targetY <= maxSize && targetZ <= maxSize ) { - if ( destination == null ) + if( destination == null ) destination = this.createNewWorld( is ); - StorageHelper.getInstance() - .swapRegions( w, destination, min.x + 1, min.y + 1, min.z + 1, 1, floorBuffer + 1, 1, targetX - 1, targetY - 1, targetZ - 1 ); + StorageHelper.getInstance().swapRegions( w, destination, min.x + 1, min.y + 1, min.z + 1, 1, floorBuffer + 1, 1, targetX - 1, targetY - 1, targetZ - 1 ); this.setStoredSize( is, targetX, targetY, targetZ ); return new TransitionResult( true, 0 ); @@ -189,7 +188,7 @@ public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorag private void setStoredSize( ItemStack is, int targetX, int targetY, int targetZ ) { - if ( is.hasTagCompound() ) + if( is.hasTagCompound() ) { NBTTagCompound c = is.getTagCompound(); int dim = c.getInteger( "StorageDim" ); @@ -199,5 +198,4 @@ public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorag WorldSettings.getInstance().setStoredSize( dim, targetX, targetY, targetZ ); } } - } diff --git a/src/main/java/appeng/items/storage/ItemViewCell.java b/src/main/java/appeng/items/storage/ItemViewCell.java index 773504c8e..912cef427 100644 --- a/src/main/java/appeng/items/storage/ItemViewCell.java +++ b/src/main/java/appeng/items/storage/ItemViewCell.java @@ -57,12 +57,12 @@ public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem MergedPriorityList myMergedList = new MergedPriorityList(); - for ( ItemStack currentViewCell : list ) + for( ItemStack currentViewCell : list ) { - if ( currentViewCell == null ) + if( currentViewCell == null ) continue; - if ( ( currentViewCell.getItem() instanceof ItemViewCell ) ) + if( ( currentViewCell.getItem() instanceof ItemViewCell ) ) { IItemList priorityList = AEApi.instance().storage().createItemList(); @@ -74,15 +74,15 @@ public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem boolean hasInverter = false; boolean hasFuzzy = false; - for ( int x = 0; x < upgrades.getSizeInventory(); x++ ) + for( int x = 0; x < upgrades.getSizeInventory(); x++ ) { ItemStack is = upgrades.getStackInSlot( x ); - if ( is != null && is.getItem() instanceof IUpgradeModule ) + if( is != null && is.getItem() instanceof IUpgradeModule ) { Upgrades u = ( (IUpgradeModule) is.getItem() ).getType( is ); - if ( u != null ) + if( u != null ) { - switch ( u ) + switch( u ) { case FUZZY: hasFuzzy = true; @@ -96,16 +96,16 @@ public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem } } - for ( int x = 0; x < config.getSizeInventory(); x++ ) + for( int x = 0; x < config.getSizeInventory(); x++ ) { ItemStack is = config.getStackInSlot( x ); - if ( is != null ) + if( is != null ) priorityList.add( AEItemStack.create( is ) ); } - if ( !priorityList.isEmpty() ) + if( !priorityList.isEmpty() ) { - if ( hasFuzzy ) + if( hasFuzzy ) myMergedList.addNewList( new FuzzyPriorityList( priorityList, fzMode ), !hasInverter ); else myMergedList.addNewList( new PrecisePriorityList( priorityList ), !hasInverter ); @@ -144,7 +144,7 @@ public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem { return FuzzyMode.valueOf( fz ); } - catch ( Throwable t ) + catch( Throwable t ) { return FuzzyMode.IGNORE_ALL; } diff --git a/src/main/java/appeng/items/tools/ToolBiometricCard.java b/src/main/java/appeng/items/tools/ToolBiometricCard.java index ae332b087..df9b07ea1 100644 --- a/src/main/java/appeng/items/tools/ToolBiometricCard.java +++ b/src/main/java/appeng/items/tools/ToolBiometricCard.java @@ -50,14 +50,14 @@ public class ToolBiometricCard extends AEBaseItem implements IBiometricCard this.setFeature( EnumSet.of( AEFeature.Security ) ); this.setMaxStackSize( 1 ); - if ( Platform.isClient() ) + if( Platform.isClient() ) MinecraftForgeClient.registerItemRenderer( this, new ToolBiometricCardRender() ); } @Override public ItemStack onItemRightClick( ItemStack is, World w, EntityPlayer p ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) { this.encode( is, p ); p.swingItem(); @@ -70,9 +70,9 @@ public class ToolBiometricCard extends AEBaseItem implements IBiometricCard @Override public boolean itemInteractionForEntity( ItemStack is, EntityPlayer par2EntityPlayer, EntityLivingBase target ) { - if ( target instanceof EntityPlayer && !par2EntityPlayer.isSneaking() ) + if( target instanceof EntityPlayer && !par2EntityPlayer.isSneaking() ) { - if ( par2EntityPlayer.capabilities.isCreativeMode ) + if( par2EntityPlayer.capabilities.isCreativeMode ) is = par2EntityPlayer.getCurrentEquippedItem(); this.encode( is, (EntityPlayer) target ); par2EntityPlayer.swingItem(); @@ -92,7 +92,7 @@ public class ToolBiometricCard extends AEBaseItem implements IBiometricCard { GameProfile username = this.getProfile( is ); - if ( username != null && username.equals( p.getGameProfile() ) ) + if( username != null && username.equals( p.getGameProfile() ) ) this.setProfile( is, null ); else this.setProfile( is, p.getGameProfile() ); @@ -103,7 +103,7 @@ public class ToolBiometricCard extends AEBaseItem implements IBiometricCard { NBTTagCompound tag = Platform.openNbtData( itemStack ); - if ( profile != null ) + if( profile != null ) { NBTTagCompound pNBT = new NBTTagCompound(); NBTUtil.func_152460_a( pNBT, profile ); @@ -117,7 +117,7 @@ public class ToolBiometricCard extends AEBaseItem implements IBiometricCard public GameProfile getProfile( ItemStack is ) { NBTTagCompound tag = Platform.openNbtData( is ); - if ( tag.hasKey( "profile" ) ) + if( tag.hasKey( "profile" ) ) return NBTUtil.func_152459_a( tag.getCompoundTag( "profile" ) ); return null; } @@ -128,9 +128,9 @@ public class ToolBiometricCard extends AEBaseItem implements IBiometricCard NBTTagCompound tag = Platform.openNbtData( is ); EnumSet result = EnumSet.noneOf( SecurityPermissions.class ); - for ( SecurityPermissions sp : SecurityPermissions.values() ) + for( SecurityPermissions sp : SecurityPermissions.values() ) { - if ( tag.getBoolean( sp.name() ) ) + if( tag.getBoolean( sp.name() ) ) result.add( sp ); } @@ -148,7 +148,7 @@ public class ToolBiometricCard extends AEBaseItem implements IBiometricCard public void removePermission( ItemStack itemStack, SecurityPermissions permission ) { NBTTagCompound tag = Platform.openNbtData( itemStack ); - if ( tag.hasKey( permission.name() ) ) + if( tag.hasKey( permission.name() ) ) tag.removeTag( permission.name() ); } @@ -169,15 +169,15 @@ public class ToolBiometricCard extends AEBaseItem implements IBiometricCard public void addCheckedInformation( ItemStack stack, EntityPlayer player, List lines, boolean displayAdditionalInformation ) { EnumSet perms = this.getPermissions( stack ); - if ( perms.isEmpty() ) + if( perms.isEmpty() ) lines.add( GuiText.NoPermissions.getLocal() ); else { String msg = null; - for ( SecurityPermissions sp : perms ) + for( SecurityPermissions sp : perms ) { - if ( msg == null ) + if( msg == null ) msg = Platform.gui_localize( sp.getUnlocalizedName() ); else msg = msg + ", " + Platform.gui_localize( sp.getUnlocalizedName() ); diff --git a/src/main/java/appeng/items/tools/ToolMemoryCard.java b/src/main/java/appeng/items/tools/ToolMemoryCard.java index 14a7b5fd7..8b05540e7 100644 --- a/src/main/java/appeng/items/tools/ToolMemoryCard.java +++ b/src/main/java/appeng/items/tools/ToolMemoryCard.java @@ -51,7 +51,7 @@ public class ToolMemoryCard extends AEBaseItem implements IMemoryCard lines.add( this.getLocalizedName( this.getSettingsName( stack ) + ".name", this.getSettingsName( stack ) ) ); NBTTagCompound data = this.getData( stack ); - if ( data.hasKey( "tooltip" ) ) + if( data.hasKey( "tooltip" ) ) lines.add( StatCollector.translateToLocal( this.getLocalizedName( data.getString( "tooltip" ) + ".name", data.getString( "tooltip" ) ) ) ); } @@ -64,14 +64,14 @@ public class ToolMemoryCard extends AEBaseItem implements IMemoryCard */ private String getLocalizedName( String... name ) { - for ( String n : name ) + for( String n : name ) { String l = StatCollector.translateToLocal( n ); - if ( !l.equals( n ) ) + if( !l.equals( n ) ) return l; } - for ( String n : name ) + for( String n : name ) return n; return ""; @@ -98,7 +98,7 @@ public class ToolMemoryCard extends AEBaseItem implements IMemoryCard { NBTTagCompound c = Platform.openNbtData( is ); NBTTagCompound o = c.getCompoundTag( "Data" ); - if ( o == null ) + if( o == null ) o = new NBTTagCompound(); return (NBTTagCompound) o.copy(); } @@ -106,10 +106,10 @@ public class ToolMemoryCard extends AEBaseItem implements IMemoryCard @Override public void notifyUser( EntityPlayer player, MemoryCardMessages msg ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; - switch ( msg ) + switch( msg ) { case SETTINGS_CLEARED: player.addChatMessage( PlayerMessages.SettingCleared.get() ); @@ -130,7 +130,7 @@ public class ToolMemoryCard extends AEBaseItem implements IMemoryCard @Override public boolean onItemUse( ItemStack is, EntityPlayer player, World w, int x, int y, int z, int side, float hx, float hy, float hz ) { - if ( player.isSneaking() && !w.isRemote ) + if( player.isSneaking() && !w.isRemote ) { IMemoryCard mem = (IMemoryCard) is.getItem(); mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); diff --git a/src/main/java/appeng/items/tools/ToolNetworkTool.java b/src/main/java/appeng/items/tools/ToolNetworkTool.java index d4cdb7338..165aa67e4 100644 --- a/src/main/java/appeng/items/tools/ToolNetworkTool.java +++ b/src/main/java/appeng/items/tools/ToolNetworkTool.java @@ -59,7 +59,7 @@ public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, public ToolNetworkTool() { - super( Optional. absent() ); + super( Optional.absent() ); this.setFeature( EnumSet.of( AEFeature.NetworkTool ) ); this.setMaxStackSize( 1 ); @@ -70,17 +70,17 @@ public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, public IGuiItemObject getGuiObject( ItemStack is, World world, int x, int y, int z ) { TileEntity te = world.getTileEntity( x, y, z ); - return new NetworkToolViewer( is, ( IGridHost ) ( te instanceof IGridHost ? te : null ) ); + return new NetworkToolViewer( is, (IGridHost) ( te instanceof IGridHost ? te : null ) ); } @Override public ItemStack onItemRightClick( ItemStack it, World w, EntityPlayer p ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) { MovingObjectPosition mop = ClientHelper.proxy.getMOP(); - if ( mop == null ) + if( mop == null ) { this.onItemUseFirst( it, p, w, 0, 0, 0, -1, 0, 0, 0 ); } @@ -90,7 +90,7 @@ public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, int j = mop.blockY; int k = mop.blockZ; - if ( w.getBlock( i, j, k ).isAir( w, i, j, k ) ) + if( w.getBlock( i, j, k ).isAir( w, i, j, k ) ) this.onItemUseFirst( it, p, w, 0, 0, 0, -1, 0, 0, 0 ); } } @@ -103,21 +103,21 @@ public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, { MovingObjectPosition mop = new MovingObjectPosition( x, y, z, side, Vec3.createVectorHelper( hitX, hitY, hitZ ) ); TileEntity te = world.getTileEntity( x, y, z ); - if ( te instanceof IPartHost ) + if( te instanceof IPartHost ) { - SelectedPart part = ( ( IPartHost ) te ).selectPart( mop.hitVec ); - if ( part.part != null ) + SelectedPart part = ( (IPartHost) te ).selectPart( mop.hitVec ); + if( part.part != null ) { - if ( part.part instanceof INetworkToolAgent && !( ( INetworkToolAgent ) part.part ).showNetworkInfo( mop ) ) + if( part.part instanceof INetworkToolAgent && !( (INetworkToolAgent) part.part ).showNetworkInfo( mop ) ) return false; } } - else if ( te instanceof INetworkToolAgent && !( ( INetworkToolAgent ) te ).showNetworkInfo( mop ) ) + else if( te instanceof INetworkToolAgent && !( (INetworkToolAgent) te ).showNetworkInfo( mop ) ) { return false; } - if ( Platform.isClient() ) + if( Platform.isClient() ) { NetworkHandler.instance.sendToServer( new PacketClick( x, y, z, side, hitX, hitY, hitZ ) ); } @@ -132,18 +132,18 @@ public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, public boolean serverSideToolLogic( ItemStack is, EntityPlayer p, World w, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { - if ( side >= 0 ) + if( side >= 0 ) { - if ( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) + if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) return false; Block b = w.getBlock( x, y, z ); - if ( b != null && !p.isSneaking() ) + if( b != null && !p.isSneaking() ) { TileEntity te = w.getTileEntity( x, y, z ); - if ( !( te instanceof IGridHost ) ) + if( !( te instanceof IGridHost ) ) { - if ( b.rotateBlock( w, x, y, z, ForgeDirection.getOrientation( side ) ) ) + if( b.rotateBlock( w, x, y, z, ForgeDirection.getOrientation( side ) ) ) { b.onNeighborBlockChange( w, x, y, z, Platform.AIR ); p.swingItem(); @@ -152,14 +152,14 @@ public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, } } - if ( !p.isSneaking() ) + if( !p.isSneaking() ) { - if ( p.openContainer instanceof AEBaseContainer ) + if( p.openContainer instanceof AEBaseContainer ) return true; TileEntity te = w.getTileEntity( x, y, z ); - if ( te instanceof IGridHost ) + if( te instanceof IGridHost ) Platform.openGUI( p, te, ForgeDirection.getOrientation( side ), GuiBridge.GUI_NETWORK_STATUS ); else Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_NETWORK_TOOL ); @@ -192,5 +192,4 @@ public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, { player.swingItem(); } - } diff --git a/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java b/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java index caf8a53be..d4b5d4c0e 100644 --- a/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java +++ b/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java @@ -40,23 +40,23 @@ public class ToolChargedStaff extends AEBasePoweredItem public ToolChargedStaff() { - super( AEConfig.instance.chargedStaffBattery, Optional. absent() ); + super( AEConfig.instance.chargedStaffBattery, Optional.absent() ); this.setFeature( EnumSet.of( AEFeature.ChargedStaff, AEFeature.PoweredTools ) ); } @Override public boolean hitEntity( ItemStack item, EntityLivingBase target, EntityLivingBase hitter ) { - if ( this.getAECurrentPower( item ) > 300 ) + if( this.getAECurrentPower( item ) > 300 ) { this.extractAEPower( item, 300 ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { - for ( int x = 0; x < 2; x++ ) + for( int x = 0; x < 2; x++ ) { - float dx = ( float ) ( Platform.getRandomFloat() * target.width + target.boundingBox.minX ); - float dy = ( float ) ( Platform.getRandomFloat() * target.height + target.boundingBox.minY ); - float dz = ( float ) ( Platform.getRandomFloat() * target.width + target.boundingBox.minZ ); + float dx = (float) ( Platform.getRandomFloat() * target.width + target.boundingBox.minX ); + float dy = (float) ( Platform.getRandomFloat() * target.height + target.boundingBox.minY ); + float dz = (float) ( Platform.getRandomFloat() * target.width + target.boundingBox.minZ ); ServerHelper.proxy.sendToAllNearExcept( null, dx, dy, dz, 32.0, target.worldObj, new PacketLightning( dx, dy, dz ) ); } } diff --git a/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java b/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java index 1af889d25..bc177dce2 100644 --- a/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java +++ b/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java @@ -87,21 +87,20 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe static { - for ( AEColor col : AEColor.values() ) + for( AEColor col : AEColor.values() ) { - if ( col == AEColor.Transparent ) + if( col == AEColor.Transparent ) continue; ORE_TO_COLOR.put( OreDictionary.getOreID( "dye" + col.name() ), col ); } - } public ToolColorApplicator() { - super( AEConfig.instance.colorApplicatorBattery, Optional. absent() ); + super( AEConfig.instance.colorApplicatorBattery, Optional.absent() ); this.setFeature( EnumSet.of( AEFeature.ColorApplicator, AEFeature.PoweredTools ) ); - if ( Platform.isClient() ) + if( Platform.isClient() ) MinecraftForgeClient.registerItemRenderer( this, new ToolColorApplicatorRender() ); } @@ -121,11 +120,11 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe ItemStack paintBall = this.getColor( is ); IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - if ( inv != null ) + if( inv != null ) { IAEItemStack option = inv.extractItems( AEItemStack.create( paintBall ), Actionable.SIMULATE, new BaseActionSource() ); - if ( option != null ) + if( option != null ) { paintBall = option.getItemStack(); paintBall.stackSize = 1; @@ -133,19 +132,19 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe else paintBall = null; - if ( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) + if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) return false; - if ( paintBall != null && paintBall.getItem() instanceof ItemSnowball ) + if( paintBall != null && paintBall.getItem() instanceof ItemSnowball ) { ForgeDirection orientation = ForgeDirection.getOrientation( side ); TileEntity te = w.getTileEntity( x, y, z ); // clean cables. - if ( te instanceof IColorableTile ) + if( te instanceof IColorableTile ) { - if ( this.getAECurrentPower( is ) > powerPerUse && ( ( IColorableTile ) te ).getColor() != AEColor.Transparent ) + if( this.getAECurrentPower( is ) > powerPerUse && ( (IColorableTile) te ).getColor() != AEColor.Transparent ) { - if ( ( ( IColorableTile ) te ).recolourBlock( orientation, AEColor.Transparent, p ) ) + if( ( (IColorableTile) te ).recolourBlock( orientation, AEColor.Transparent, p ) ) { inv.extractItems( AEItemStack.create( paintBall ), Actionable.MODULATE, new BaseActionSource() ); this.extractAEPower( is, powerPerUse ); @@ -157,33 +156,31 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe // clean paint balls.. Block testBlk = w.getBlock( x + orientation.offsetX, y + orientation.offsetY, z + orientation.offsetZ ); TileEntity painted = w.getTileEntity( x + orientation.offsetX, y + orientation.offsetY, z + orientation.offsetZ ); - if ( this.getAECurrentPower( is ) > powerPerUse && testBlk instanceof BlockPaint && painted instanceof TilePaint ) + if( this.getAECurrentPower( is ) > powerPerUse && testBlk instanceof BlockPaint && painted instanceof TilePaint ) { inv.extractItems( AEItemStack.create( paintBall ), Actionable.MODULATE, new BaseActionSource() ); this.extractAEPower( is, powerPerUse ); - ( ( TilePaint ) painted ).cleanSide( orientation.getOpposite() ); + ( (TilePaint) painted ).cleanSide( orientation.getOpposite() ); return true; } } - else if ( paintBall != null ) + else if( paintBall != null ) { AEColor color = this.getColorFromItem( paintBall ); - if ( color != null && this.getAECurrentPower( is ) > powerPerUse ) + if( color != null && this.getAECurrentPower( is ) > powerPerUse ) { - if ( color != AEColor.Transparent - && this.recolourBlock( blk, ForgeDirection.getOrientation( side ), w, x, y, z, ForgeDirection.getOrientation( side ), color, p ) ) + if( color != AEColor.Transparent && this.recolourBlock( blk, ForgeDirection.getOrientation( side ), w, x, y, z, ForgeDirection.getOrientation( side ), color, p ) ) { inv.extractItems( AEItemStack.create( paintBall ), Actionable.MODULATE, new BaseActionSource() ); this.extractAEPower( is, powerPerUse ); return true; } } - } } - if ( p.isSneaking() ) + if( p.isSneaking() ) { this.cycleColors( is, paintBall, 1 ); } @@ -198,7 +195,7 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe AEColor selected = this.getActiveColor( par1ItemStack ); - if ( selected != null && Platform.isClient() ) + if( selected != null && Platform.isClient() ) extra = Platform.gui_localize( selected.unlocalizedName ); return super.getItemStackDisplayName( par1ItemStack ) + " - " + extra; @@ -211,24 +208,24 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe public AEColor getColorFromItem( ItemStack paintBall ) { - if ( paintBall == null ) + if( paintBall == null ) return null; - if ( paintBall.getItem() instanceof ItemSnowball ) + if( paintBall.getItem() instanceof ItemSnowball ) return AEColor.Transparent; - if ( paintBall.getItem() instanceof ItemPaintBall ) + if( paintBall.getItem() instanceof ItemPaintBall ) { - ItemPaintBall ipb = ( ItemPaintBall ) paintBall.getItem(); + ItemPaintBall ipb = (ItemPaintBall) paintBall.getItem(); return ipb.getColor( paintBall ); } else { int[] id = OreDictionary.getOreIDs( paintBall ); - for ( int oreID : id ) + for( int oreID : id ) { - if ( ORE_TO_COLOR.containsKey( oreID ) ) + if( ORE_TO_COLOR.containsKey( oreID ) ) return ORE_TO_COLOR.get( oreID ); } } @@ -239,11 +236,11 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe public ItemStack getColor( ItemStack is ) { NBTTagCompound c = is.getTagCompound(); - if ( c != null && c.hasKey( "color" ) ) + if( c != null && c.hasKey( "color" ) ) { NBTTagCompound color = c.getCompoundTag( "color" ); ItemStack oldColor = ItemStack.loadItemStackFromNBT( color ); - if ( oldColor != null ) + if( oldColor != null ) return oldColor; } @@ -255,56 +252,56 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe ItemStack newColor = null; IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - if ( inv != null ) + if( inv != null ) { IItemList itemList = inv.getAvailableItems( AEApi.instance().storage().createItemList() ); - if ( anchor == null ) + if( anchor == null ) { IAEItemStack firstItem = itemList.getFirstItem(); - if ( firstItem != null ) + if( firstItem != null ) newColor = firstItem.getItemStack(); } else { LinkedList list = new LinkedList(); - for ( IAEItemStack i : itemList ) + for( IAEItemStack i : itemList ) list.add( i ); - Collections.sort( list, new Comparator(){ + Collections.sort( list, new Comparator() + { @Override public int compare( IAEItemStack a, IAEItemStack b ) { return ItemSorters.compareInt( a.getItemDamage(), b.getItemDamage() ); } - } ); - if ( list.size() <= 0 ) + if( list.size() <= 0 ) return null; IAEItemStack where = list.getFirst(); int cycles = 1 + list.size(); - while ( cycles > 0 && !where.equals( anchor ) ) + while( cycles > 0 && !where.equals( anchor ) ) { list.addLast( list.removeFirst() ); cycles--; where = list.getFirst(); } - if ( scrollOffset > 0 ) + if( scrollOffset > 0 ) list.addLast( list.removeFirst() ); - if ( scrollOffset < 0 ) + if( scrollOffset < 0 ) list.addFirst( list.removeLast() ); return list.get( 0 ).getItemStack(); } } - if ( newColor != null ) + if( newColor != null ) this.setColor( is, newColor ); return newColor; @@ -313,7 +310,7 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe public void setColor( ItemStack is, ItemStack newColor ) { NBTTagCompound data = Platform.openNbtData( is ); - if ( newColor == null ) + if( newColor == null ) data.removeTag( "color" ); else { @@ -325,62 +322,62 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe private boolean recolourBlock( Block blk, ForgeDirection side, World w, int x, int y, int z, ForgeDirection orientation, AEColor newColor, EntityPlayer p ) { - if ( blk == Blocks.carpet ) + if( blk == Blocks.carpet ) { int meta = w.getBlockMetadata( x, y, z ); - if ( newColor.ordinal() == meta ) + if( newColor.ordinal() == meta ) return false; return w.setBlock( x, y, z, Blocks.carpet, newColor.ordinal(), 3 ); } - if ( blk == Blocks.glass ) + if( blk == Blocks.glass ) { return w.setBlock( x, y, z, Blocks.stained_glass, newColor.ordinal(), 3 ); } - if ( blk == Blocks.stained_glass ) + if( blk == Blocks.stained_glass ) { int meta = w.getBlockMetadata( x, y, z ); - if ( newColor.ordinal() == meta ) + if( newColor.ordinal() == meta ) return false; return w.setBlock( x, y, z, Blocks.stained_glass, newColor.ordinal(), 3 ); } - if ( blk == Blocks.glass_pane ) + if( blk == Blocks.glass_pane ) { return w.setBlock( x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3 ); } - if ( blk == Blocks.stained_glass_pane ) + if( blk == Blocks.stained_glass_pane ) { int meta = w.getBlockMetadata( x, y, z ); - if ( newColor.ordinal() == meta ) + if( newColor.ordinal() == meta ) return false; return w.setBlock( x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3 ); } - if ( blk == Blocks.hardened_clay ) + if( blk == Blocks.hardened_clay ) { return w.setBlock( x, y, z, Blocks.stained_hardened_clay, newColor.ordinal(), 3 ); } - if ( blk == Blocks.stained_hardened_clay ) + if( blk == Blocks.stained_hardened_clay ) { int meta = w.getBlockMetadata( x, y, z ); - if ( newColor.ordinal() == meta ) + if( newColor.ordinal() == meta ) return false; return w.setBlock( x, y, z, Blocks.stained_hardened_clay, newColor.ordinal(), 3 ); } - if ( blk instanceof BlockCableBus ) - return ( ( BlockCableBus ) blk ).recolourBlock( w, x, y, z, side, newColor.ordinal(), p ); + if( blk instanceof BlockCableBus ) + return ( (BlockCableBus) blk ).recolourBlock( w, x, y, z, side, newColor.ordinal(), p ); return blk.recolourBlock( w, x, y, z, side, newColor.ordinal() ); } public void cycleColors( ItemStack is, ItemStack paintBall, int i ) { - if ( paintBall == null ) + if( paintBall == null ) { this.setColor( is, this.getColor( is ) ); } @@ -397,10 +394,10 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - if ( cdi instanceof CellInventoryHandler ) + if( cdi instanceof CellInventoryHandler ) { - ICellInventory cd = ( ( ICellInventoryHandler ) cdi ).getCellInv(); - if ( cd != null ) + ICellInventory cd = ( (ICellInventoryHandler) cdi ).getCellInv(); + if( cd != null ) { lines.add( cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); lines.add( cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); @@ -429,17 +426,17 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe @Override public boolean isBlackListed( ItemStack cellItem, IAEItemStack requestedAddition ) { - if ( requestedAddition != null ) + if( requestedAddition != null ) { int[] id = OreDictionary.getOreIDs( requestedAddition.getItemStack() ); - for ( int x : id ) + for( int x : id ) { - if ( ORE_TO_COLOR.containsKey( x ) ) + if( ORE_TO_COLOR.containsKey( x ) ) return false; } - if ( requestedAddition.getItem() instanceof ItemSnowball ) + if( requestedAddition.getItem() instanceof ItemSnowball ) return false; return !( requestedAddition.getItem() instanceof ItemPaintBall && requestedAddition.getItemDamage() < 20 ); @@ -497,7 +494,7 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe { return FuzzyMode.valueOf( fz ); } - catch ( Throwable t ) + catch( Throwable t ) { return FuzzyMode.IGNORE_ALL; } @@ -514,5 +511,4 @@ public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCe { this.cycleColors( is, this.getColor( is ), up ? 1 : -1 ); } - } diff --git a/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java b/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java index 0c76d7b8d..2aa7a101f 100644 --- a/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java +++ b/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java @@ -113,9 +113,9 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT @Override public boolean equals( Object obj ) { - if ( obj == null ) + if( obj == null ) return false; - if ( this.getClass() != obj.getClass() ) + if( this.getClass() != obj.getClass() ) return false; InWorldToolOperationIngredient other = (InWorldToolOperationIngredient) obj; return this.blockID == other.blockID && this.metadata == other.metadata; @@ -126,12 +126,12 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT { InWorldToolOperationResult r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, metadata ) ); - if ( r == null ) + if( r == null ) { r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); } - if ( r.BlockItem != null ) + if( r.BlockItem != null ) { w.setBlock( x, y, z, Block.getBlockFromItem( r.BlockItem.getItem() ), r.BlockItem.getItemDamage(), 3 ); } @@ -140,7 +140,7 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT w.setBlock( x, y, z, Platform.AIR, 0, 3 ); } - if ( r.Drops != null ) + if( r.Drops != null ) { Platform.spawnDrops( w, x, y, z, r.Drops ); } @@ -150,7 +150,7 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT { InWorldToolOperationResult r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, metadata ) ); - if ( r == null ) + if( r == null ) { r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); } @@ -162,12 +162,12 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT { InWorldToolOperationResult r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, metadata ) ); - if ( r == null ) + if( r == null ) { r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); } - if ( r.BlockItem != null ) + if( r.BlockItem != null ) { w.setBlock( x, y, z, Block.getBlockFromItem( r.BlockItem.getItem() ), r.BlockItem.getItemDamage(), 3 ); } @@ -176,7 +176,7 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT w.setBlock( x, y, z, Platform.AIR, 0, 3 ); } - if ( r.Drops != null ) + if( r.Drops != null ) { Platform.spawnDrops( w, x, y, z, r.Drops ); } @@ -186,7 +186,7 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT { InWorldToolOperationResult r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, metadata ) ); - if ( r == null ) + if( r == null ) { r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); } @@ -197,7 +197,7 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT @Override public boolean hitEntity( ItemStack item, EntityLivingBase target, EntityLivingBase hitter ) { - if ( this.getAECurrentPower( item ) > 1600 ) + if( this.getAECurrentPower( item ) > 1600 ) { this.extractAEPower( item, 1600 ); target.setFire( 8 ); @@ -211,19 +211,19 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT { MovingObjectPosition target = this.getMovingObjectPositionFromPlayer( w, p, true ); - if ( target == null ) + if( target == null ) return item; else { - if ( target.typeOfHit == MovingObjectType.BLOCK ) + if( target.typeOfHit == MovingObjectType.BLOCK ) { int x = target.blockX; int y = target.blockY; int z = target.blockZ; - if ( w.getBlock( x, y, z ).getMaterial() == Material.lava || w.getBlock( x, y, z ).getMaterial() == Material.water ) + if( w.getBlock( x, y, z ).getMaterial() == Material.lava || w.getBlock( x, y, z ).getMaterial() == Material.water ) { - if ( Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) + if( Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) { this.onItemUse( item, p, w, x, y, z, 0, 0.0F, 0.0F, 0.0F ); } @@ -237,17 +237,17 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT @Override public boolean onItemUse( ItemStack item, EntityPlayer p, World w, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { - if ( this.getAECurrentPower( item ) > 1600 ) + if( this.getAECurrentPower( item ) > 1600 ) { - if ( !p.canPlayerEdit( x, y, z, side, item ) ) + if( !p.canPlayerEdit( x, y, z, side, item ) ) return false; Block blockID = w.getBlock( x, y, z ); int metadata = w.getBlockMetadata( x, y, z ); - if ( p.isSneaking() ) + if( p.isSneaking() ) { - if ( this.canCool( blockID, metadata ) ) + if( this.canCool( blockID, metadata ) ) { this.extractAEPower( item, 1600 ); this.cool( blockID, metadata, w, x, y, z ); @@ -256,21 +256,21 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT } else { - if ( blockID instanceof BlockTNT ) + if( blockID instanceof BlockTNT ) { w.setBlock( x, y, z, Platform.AIR, 0, 3 ); ( (BlockTNT) blockID ).func_150114_a( w, x, y, z, 1, p ); return true; } - if ( blockID instanceof BlockTinyTNT ) + if( blockID instanceof BlockTinyTNT ) { w.setBlock( x, y, z, Platform.AIR, 0, 3 ); ( (BlockTinyTNT) blockID ).startFuse( w, x, y, z, p ); return true; } - if ( this.canHeat( blockID, metadata ) ) + if( this.canHeat( blockID, metadata ) ) { this.extractAEPower( item, 1600 ); this.heat( blockID, metadata, w, x, y, z ); @@ -282,15 +282,15 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT boolean hasFurnaceable = false; boolean canFurnaceable = true; - for ( ItemStack i : stack ) + for( ItemStack i : stack ) { ItemStack result = FurnaceRecipes.smelting().getSmeltingResult( i ); - if ( result != null ) + if( result != null ) { - if ( result.getItem() instanceof ItemBlock ) + if( result.getItem() instanceof ItemBlock ) { - if ( Block.getBlockFromItem( result.getItem() ) == blockID && result.getItem().getDamage( result ) == metadata ) + if( Block.getBlockFromItem( result.getItem() ) == blockID && result.getItem().getDamage( result ) == metadata ) { canFurnaceable = false; } @@ -305,13 +305,13 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT } } - if ( hasFurnaceable && canFurnaceable ) + if( hasFurnaceable && canFurnaceable ) { this.extractAEPower( item, 1600 ); InWorldToolOperationResult or = InWorldToolOperationResult.getBlockOperationResult( out.toArray( new ItemStack[out.size()] ) ); w.playSoundEffect( x + 0.5D, y + 0.5D, z + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F ); - if ( or.BlockItem == null ) + if( or.BlockItem == null ) { w.setBlock( x, y, z, Platform.AIR, 0, 3 ); } @@ -320,7 +320,7 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT w.setBlock( x, y, z, Block.getBlockFromItem( or.BlockItem.getItem() ), or.BlockItem.getItemDamage(), 3 ); } - if ( or.Drops != null ) + if( or.Drops != null ) { Platform.spawnDrops( w, x, y, z, or.Drops ); } @@ -334,10 +334,10 @@ public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockT y += dir.offsetY; z += dir.offsetZ; - if ( !p.canPlayerEdit( x, y, z, side, item ) ) + if( !p.canPlayerEdit( x, y, z, side, item ) ) return false; - if ( w.isAirBlock( x, y, z ) ) + if( w.isAirBlock( x, y, z ) ) { this.extractAEPower( item, 1600 ); w.playSoundEffect( x + 0.5D, y + 0.5D, z + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F ); diff --git a/src/main/java/appeng/items/tools/powered/ToolMassCannon.java b/src/main/java/appeng/items/tools/powered/ToolMassCannon.java index b337c3dbb..fe981db32 100644 --- a/src/main/java/appeng/items/tools/powered/ToolMassCannon.java +++ b/src/main/java/appeng/items/tools/powered/ToolMassCannon.java @@ -83,7 +83,7 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell public ToolMassCannon() { - super( AEConfig.instance.matterCannonBattery, Optional. absent() ); + super( AEConfig.instance.matterCannonBattery, Optional.absent() ); this.setFeature( EnumSet.of( AEFeature.MatterCannon, AEFeature.PoweredTools ) ); } @@ -101,10 +101,10 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - if ( cdi instanceof CellInventoryHandler ) + if( cdi instanceof CellInventoryHandler ) { - ICellInventory cd = ( ( ICellInventoryHandler ) cdi ).getCellInv(); - if ( cd != null ) + ICellInventory cd = ( (ICellInventoryHandler) cdi ).getCellInv(); + if( cd != null ) { lines.add( cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); lines.add( cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); @@ -115,37 +115,37 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell @Override public ItemStack onItemRightClick( ItemStack item, World w, EntityPlayer p ) { - if ( this.getAECurrentPower( item ) > 1600 ) + if( this.getAECurrentPower( item ) > 1600 ) { int shots = 1; - CellUpgrades cu = ( CellUpgrades ) this.getUpgradesInventory( item ); - if ( cu != null ) + CellUpgrades cu = (CellUpgrades) this.getUpgradesInventory( item ); + if( cu != null ) shots += cu.getInstalledUpgrades( Upgrades.SPEED ); IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( item, null, StorageChannel.ITEMS ); - if ( inv != null ) + if( inv != null ) { IItemList itemList = inv.getAvailableItems( AEApi.instance().storage().createItemList() ); IAEStack aeAmmo = itemList.getFirstItem(); - if ( aeAmmo instanceof IAEItemStack ) + if( aeAmmo instanceof IAEItemStack ) { - shots = Math.min( shots, ( int ) aeAmmo.getStackSize() ); - for ( int sh = 0; sh < shots; sh++ ) + shots = Math.min( shots, (int) aeAmmo.getStackSize() ); + for( int sh = 0; sh < shots; sh++ ) { this.extractAEPower( item, 1600 ); - if ( Platform.isClient() ) + if( Platform.isClient() ) return item; aeAmmo.setStackSize( 1 ); - ItemStack ammo = ( ( IAEItemStack ) aeAmmo ).getItemStack(); - if ( ammo == null ) + ItemStack ammo = ( (IAEItemStack) aeAmmo ).getItemStack(); + if( ammo == null ) return item; ammo.stackSize = 1; aeAmmo = inv.extractItems( aeAmmo, Actionable.MODULATE, new PlayerSource( p, null ) ); - if ( aeAmmo == null ) + if( aeAmmo == null ) return item; float f = 1.0F; @@ -155,8 +155,8 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell double d1 = p.prevPosY + ( p.posY - p.prevPosY ) * f + 1.62D - p.yOffset; double d2 = p.prevPosZ + ( p.posZ - p.prevPosZ ) * f; Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); - float f3 = MathHelper.cos( -f2 * 0.017453292F - ( float ) Math.PI ); - float f4 = MathHelper.sin( -f2 * 0.017453292F - ( float ) Math.PI ); + float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); + float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); float f5 = -MathHelper.cos( -f1 * 0.017453292F ); float f6 = MathHelper.sin( -f1 * 0.017453292F ); float f7 = f4 * f5; @@ -168,10 +168,10 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell direction.normalize(); float penetration = AEApi.instance().registries().matterCannon().getPenetration( ammo ); // 196.96655f; - if ( penetration <= 0 ) + if( penetration <= 0 ) { - ItemStack type = ( ( IAEItemStack ) aeAmmo ).getItemStack(); - if ( type.getItem() instanceof ItemPaintBall ) + ItemStack type = ( (IAEItemStack) aeAmmo ).getItemStack(); + if( type.getItem() instanceof ItemPaintBall ) { this.shootPaintBalls( type, w, p, vec3, vec31, direction, d0, d1, d2 ); } @@ -181,12 +181,11 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell { this.standardAmmo( penetration, w, p, vec3, vec31, direction, d0, d1, d2 ); } - } } else { - if ( Platform.isServer() ) + if( Platform.isServer() ) p.addChatMessage( PlayerMessages.AmmoDepleted.get() ); return item; } @@ -197,25 +196,23 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell private void shootPaintBalls( ItemStack type, World w, EntityPlayer p, Vec3 vec3, Vec3 vec31, Vec3 direction, double d0, double d1, double d2 ) { - AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), - Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), - Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); + AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); Entity entity = null; List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); double closest = 9999999.0D; int l; - for ( l = 0; l < list.size(); ++l ) + for( l = 0; l < list.size(); ++l ) { - Entity entity1 = ( Entity ) list.get( l ); + Entity entity1 = (Entity) list.get( l ); - if ( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) + if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) { - if ( entity1.isEntityAlive() ) + if( entity1.isEntityAlive() ) { // prevent killing / flying of mounts. - if ( entity1.riddenByEntity == p ) + if( entity1.riddenByEntity == p ) continue; float f1 = 0.3F; @@ -223,11 +220,11 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); - if ( movingObjectPosition != null ) + if( movingObjectPosition != null ) { double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); - if ( nd < closest ) + if( nd < closest ) { entity = entity1; closest = nd; @@ -240,49 +237,47 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell MovingObjectPosition pos = w.rayTraceBlocks( vec3, vec31, false ); Vec3 vec = Vec3.createVectorHelper( d0, d1, d2 ); - if ( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) + if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) { pos = new MovingObjectPosition( entity ); } - else if ( entity != null && pos == null ) + else if( entity != null && pos == null ) { pos = new MovingObjectPosition( entity ); } try { - CommonHelper.proxy.sendToAllNearExcept( null, d0, d1, d2, 128, w, new PacketMatterCannon( d0, d1, d2, ( float ) direction.xCoord, - ( float ) direction.yCoord, ( float ) direction.zCoord, ( byte ) ( pos == null ? 32 : pos.hitVec.squareDistanceTo( vec ) + 1 ) ) ); - + CommonHelper.proxy.sendToAllNearExcept( null, d0, d1, d2, 128, w, new PacketMatterCannon( d0, d1, d2, (float) direction.xCoord, (float) direction.yCoord, (float) direction.zCoord, (byte) ( pos == null ? 32 : pos.hitVec.squareDistanceTo( vec ) + 1 ) ) ); } - catch ( Exception err ) + catch( Exception err ) { AELog.error( err ); } - if ( pos != null && type != null && type.getItem() instanceof ItemPaintBall ) + if( pos != null && type != null && type.getItem() instanceof ItemPaintBall ) { - ItemPaintBall ipb = ( ItemPaintBall ) type.getItem(); + ItemPaintBall ipb = (ItemPaintBall) type.getItem(); AEColor col = ipb.getColor( type ); // boolean lit = ipb.isLumen( type ); - if ( pos.typeOfHit == MovingObjectType.ENTITY ) + if( pos.typeOfHit == MovingObjectType.ENTITY ) { int id = pos.entityHit.getEntityId(); PlayerColor marker = new PlayerColor( id, col, 20 * 30 ); TickHandler.INSTANCE.getPlayerColors().put( id, marker ); - if ( pos.entityHit instanceof EntitySheep ) + if( pos.entityHit instanceof EntitySheep ) { - EntitySheep sh = ( EntitySheep ) pos.entityHit; + EntitySheep sh = (EntitySheep) pos.entityHit; sh.setFleeceColor( col.ordinal() ); } pos.entityHit.attackEntityFrom( DamageSource.causePlayerDamage( p ), 0 ); NetworkHandler.instance.sendToAll( marker.getPacket() ); } - else if ( pos.typeOfHit == MovingObjectType.BLOCK ) + else if( pos.typeOfHit == MovingObjectType.BLOCK ) { ForgeDirection side = ForgeDirection.getOrientation( pos.sideHit ); @@ -290,57 +285,54 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell int y = pos.blockY + side.offsetY; int z = pos.blockZ + side.offsetZ; - if ( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) + if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) return; Block whatsThere = w.getBlock( x, y, z ); - if ( whatsThere.isReplaceable( w, x, y, z ) && w.isAirBlock( x, y, z ) ) + if( whatsThere.isReplaceable( w, x, y, z ) && w.isAirBlock( x, y, z ) ) { - for ( Block paintBlock : AEApi.instance().definitions().blocks().paint().maybeBlock().asSet() ) + for( Block paintBlock : AEApi.instance().definitions().blocks().paint().maybeBlock().asSet() ) { w.setBlock( x, y, z, paintBlock, 0, 3 ); } } TileEntity te = w.getTileEntity( x, y, z ); - if ( te instanceof TilePaint ) + if( te instanceof TilePaint ) { pos.hitVec.xCoord -= x; pos.hitVec.yCoord -= y; pos.hitVec.zCoord -= z; - ( ( TilePaint ) te ).addBlot( type, side.getOpposite(), pos.hitVec ); + ( (TilePaint) te ).addBlot( type, side.getOpposite(), pos.hitVec ); } } - } } private void standardAmmo( float penetration, World w, EntityPlayer p, Vec3 vec3, Vec3 vec31, Vec3 direction, double d0, double d1, double d2 ) { boolean hasDestroyedSomething = true; - while ( penetration > 0 && hasDestroyedSomething ) + while( penetration > 0 && hasDestroyedSomething ) { hasDestroyedSomething = false; - AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), - Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), - Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); + AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); Entity entity = null; List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); double closest = 9999999.0D; int l; - for ( l = 0; l < list.size(); ++l ) + for( l = 0; l < list.size(); ++l ) { - Entity entity1 = ( Entity ) list.get( l ); + Entity entity1 = (Entity) list.get( l ); - if ( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) + if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) { - if ( entity1.isEntityAlive() ) + if( entity1.isEntityAlive() ) { // prevent killing / flying of mounts. - if ( entity1.riddenByEntity == p ) + if( entity1.riddenByEntity == p ) continue; float f1 = 0.3F; @@ -348,11 +340,11 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); - if ( movingObjectPosition != null ) + if( movingObjectPosition != null ) { double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); - if ( nd < closest ) + if( nd < closest ) { entity = entity1; closest = nd; @@ -364,58 +356,56 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell Vec3 vec = Vec3.createVectorHelper( d0, d1, d2 ); MovingObjectPosition pos = w.rayTraceBlocks( vec3, vec31, true ); - if ( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) + if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) { pos = new MovingObjectPosition( entity ); } - else if ( entity != null && pos == null ) + else if( entity != null && pos == null ) { pos = new MovingObjectPosition( entity ); } try { - CommonHelper.proxy.sendToAllNearExcept( null, d0, d1, d2, 128, w, new PacketMatterCannon( d0, d1, d2, ( float ) direction.xCoord, - ( float ) direction.yCoord, ( float ) direction.zCoord, ( byte ) ( pos == null ? 32 : pos.hitVec.squareDistanceTo( vec ) + 1 ) ) ); - + CommonHelper.proxy.sendToAllNearExcept( null, d0, d1, d2, 128, w, new PacketMatterCannon( d0, d1, d2, (float) direction.xCoord, (float) direction.yCoord, (float) direction.zCoord, (byte) ( pos == null ? 32 : pos.hitVec.squareDistanceTo( vec ) + 1 ) ) ); } - catch ( Exception err ) + catch( Exception err ) { AELog.error( err ); } - if ( pos != null ) + if( pos != null ) { DamageSource dmgSrc = DamageSource.causePlayerDamage( p ); dmgSrc.damageType = "masscannon"; - if ( pos.typeOfHit == MovingObjectType.ENTITY ) + if( pos.typeOfHit == MovingObjectType.ENTITY ) { - int dmg = ( int ) Math.ceil( penetration / 20.0f ); - if ( pos.entityHit instanceof EntityLivingBase ) + int dmg = (int) Math.ceil( penetration / 20.0f ); + if( pos.entityHit instanceof EntityLivingBase ) { - EntityLivingBase el = ( EntityLivingBase ) pos.entityHit; + EntityLivingBase el = (EntityLivingBase) pos.entityHit; penetration -= dmg; el.knockBack( p, 0, -direction.xCoord, -direction.zCoord ); // el.knockBack( p, 0, vec3.xCoord, // vec3.zCoord ); el.attackEntityFrom( dmgSrc, dmg ); - if ( !el.isEntityAlive() ) + if( !el.isEntityAlive() ) hasDestroyedSomething = true; } - else if ( pos.entityHit instanceof EntityItem ) + else if( pos.entityHit instanceof EntityItem ) { hasDestroyedSomething = true; pos.entityHit.setDead(); } - else if ( pos.entityHit.attackEntityFrom( dmgSrc, dmg ) ) + else if( pos.entityHit.attackEntityFrom( dmgSrc, dmg ) ) { hasDestroyedSomething = true; } } - else if ( pos.typeOfHit == MovingObjectType.BLOCK ) + else if( pos.typeOfHit == MovingObjectType.BLOCK ) { - if ( !AEConfig.instance.isFeatureEnabled( AEFeature.MassCannonBlockDamage ) ) + if( !AEConfig.instance.isFeatureEnabled( AEFeature.MassCannonBlockDamage ) ) penetration = 0; else { @@ -424,9 +414,9 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell // pos.blockX, pos.blockY, pos.blockZ ); float hardness = b.getBlockHardness( w, pos.blockX, pos.blockY, pos.blockZ ) * 9.0f; - if ( hardness >= 0.0 ) + if( hardness >= 0.0 ) { - if ( penetration > hardness && Platform.hasPermissions( new DimensionalCoord( w, pos.blockX, pos.blockY, pos.blockZ ), p ) ) + if( penetration > hardness && Platform.hasPermissions( new DimensionalCoord( w, pos.blockX, pos.blockY, pos.blockZ ), p ) ) { hasDestroyedSomething = true; penetration -= hardness; @@ -467,7 +457,7 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell { return FuzzyMode.valueOf( fz ); } - catch ( Throwable t ) + catch( Throwable t ) { return FuzzyMode.IGNORE_ALL; } @@ -501,10 +491,10 @@ public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell public boolean isBlackListed( ItemStack cellItem, IAEItemStack requestedAddition ) { float pen = AEApi.instance().registries().matterCannon().getPenetration( requestedAddition.getItemStack() ); - if ( pen > 0 ) + if( pen > 0 ) return false; - if ( requestedAddition.getItem() instanceof ItemPaintBall ) + if( requestedAddition.getItem() instanceof ItemPaintBall ) return false; return true; diff --git a/src/main/java/appeng/items/tools/powered/ToolPortableCell.java b/src/main/java/appeng/items/tools/powered/ToolPortableCell.java index 5fd4ec728..05d40f815 100644 --- a/src/main/java/appeng/items/tools/powered/ToolPortableCell.java +++ b/src/main/java/appeng/items/tools/powered/ToolPortableCell.java @@ -61,17 +61,10 @@ public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, { public ToolPortableCell() { - super( AEConfig.instance.portableCellBattery, Optional. absent() ); + super( AEConfig.instance.portableCellBattery, Optional.absent() ); this.setFeature( EnumSet.of( AEFeature.PortableCell, AEFeature.StorageCells, AEFeature.PoweredTools ) ); } - @SideOnly(Side.CLIENT) - @Override - public boolean isFull3D() - { - return false; - } - @Override public ItemStack onItemRightClick( ItemStack item, World w, EntityPlayer player ) { @@ -79,6 +72,13 @@ public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, return item; } + @SideOnly( Side.CLIENT ) + @Override + public boolean isFull3D() + { + return false; + } + @Override public void addCheckedInformation( ItemStack stack, EntityPlayer player, List lines, boolean displayAdditionalInformation ) { @@ -86,10 +86,10 @@ public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - if ( cdi instanceof CellInventoryHandler ) + if( cdi instanceof CellInventoryHandler ) { - ICellInventory cd = ( ( ICellInventoryHandler ) cdi ).getCellInv(); - if ( cd != null ) + ICellInventory cd = ( (ICellInventoryHandler) cdi ).getCellInv(); + if( cd != null ) { lines.add( cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); lines.add( cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); @@ -171,7 +171,7 @@ public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, { return FuzzyMode.valueOf( fz ); } - catch ( Throwable t ) + catch( Throwable t ) { return FuzzyMode.IGNORE_ALL; } diff --git a/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java b/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java index 9bd518a90..215800ed8 100644 --- a/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java +++ b/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java @@ -54,17 +54,10 @@ public class ToolWirelessTerminal extends AEBasePoweredItem implements IWireless public ToolWirelessTerminal() { - super( AEConfig.instance.wirelessTerminalBattery, Optional. absent() ); + super( AEConfig.instance.wirelessTerminalBattery, Optional.absent() ); this.setFeature( EnumSet.of( AEFeature.WirelessAccessTerminal, AEFeature.PoweredTools ) ); } - @SideOnly(Side.CLIENT) - @Override - public boolean isFull3D() - { - return false; - } - @Override public ItemStack onItemRightClick( ItemStack item, World w, EntityPlayer player ) { @@ -72,19 +65,26 @@ public class ToolWirelessTerminal extends AEBasePoweredItem implements IWireless return item; } + @SideOnly( Side.CLIENT ) + @Override + public boolean isFull3D() + { + return false; + } + @Override public void addCheckedInformation( ItemStack stack, EntityPlayer player, List lines, boolean displayAdditionalInformation ) { super.addCheckedInformation( stack, player, lines, displayAdditionalInformation ); - if ( stack.hasTagCompound() ) + if( stack.hasTagCompound() ) { NBTTagCompound tag = Platform.openNbtData( stack ); - if ( tag != null ) + if( tag != null ) { String encKey = tag.getString( "encryptionKey" ); - if ( encKey == null || encKey.isEmpty() ) + if( encKey == null || encKey.isEmpty() ) lines.add( GuiText.Unlinked.getLocal() ); else lines.add( GuiText.Linked.getLocal() ); @@ -115,7 +115,8 @@ public class ToolWirelessTerminal extends AEBasePoweredItem implements IWireless @Override public IConfigManager getConfigManager( final ItemStack target ) { - final ConfigManager out = new ConfigManager( new IConfigManagerHost(){ + final ConfigManager out = new ConfigManager( new IConfigManagerHost() + { @Override public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) @@ -123,14 +124,13 @@ public class ToolWirelessTerminal extends AEBasePoweredItem implements IWireless NBTTagCompound data = Platform.openNbtData( target ); manager.writeToNBT( data ); } - } ); out.registerSetting( Settings.SORT_BY, SortOrder.NAME ); out.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); out.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - out.readFromNBT( ( NBTTagCompound ) Platform.openNbtData( target ).copy() ); + out.readFromNBT( (NBTTagCompound) Platform.openNbtData( target ).copy() ); return out; } @@ -148,5 +148,4 @@ public class ToolWirelessTerminal extends AEBasePoweredItem implements IWireless tag.setString( "encryptionKey", encKey ); tag.setString( "name", name ); } - } diff --git a/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java b/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java index be49139e7..7aa442d4b 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java +++ b/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java @@ -60,16 +60,14 @@ public abstract class AERootPoweredItem extends AEBaseItem implements IAEItemPow double internalCurrentPower = 0; double internalMaxPower = this.getAEMaxPower( stack ); - if ( tag != null ) + if( tag != null ) { internalCurrentPower = tag.getDouble( "internalCurrentPower" ); } double percent = internalCurrentPower / internalMaxPower; - lines.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) - + Platform.gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); - + lines.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) + Platform.gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); } @Override @@ -114,15 +112,50 @@ public abstract class AERootPoweredItem extends AEBaseItem implements IAEItemPow } + private double getInternalBattery( ItemStack is, batteryOperation op, double adjustment ) + { + NBTTagCompound data = Platform.openNbtData( is ); + + double currentStorage = data.getDouble( this.POWER_NBT_KEY ); + double maxStorage = this.getAEMaxPower( is ); + + switch( op ) + { + case INJECT: + currentStorage += adjustment; + if( currentStorage > maxStorage ) + { + double diff = currentStorage - maxStorage; + data.setDouble( this.POWER_NBT_KEY, maxStorage ); + return diff; + } + data.setDouble( this.POWER_NBT_KEY, currentStorage ); + return 0; + case EXTRACT: + if( currentStorage > adjustment ) + { + currentStorage -= adjustment; + data.setDouble( this.POWER_NBT_KEY, currentStorage ); + return adjustment; + } + data.setDouble( this.POWER_NBT_KEY, 0 ); + return currentStorage; + default: + break; + } + + return currentStorage; + } + /** * inject external */ double injectExternalPower( PowerUnits input, ItemStack is, double amount, boolean simulate ) { - if ( simulate ) + if( simulate ) { - int requiredEU = ( int ) PowerUnits.AE.convertTo( PowerUnits.EU, this.getAEMaxPower( is ) - this.getAECurrentPower( is ) ); - if ( amount < requiredEU ) + int requiredEU = (int) PowerUnits.AE.convertTo( PowerUnits.EU, this.getAEMaxPower( is ) - this.getAECurrentPower( is ) ); + if( amount < requiredEU ) return 0; return amount - requiredEU; } @@ -145,41 +178,6 @@ public abstract class AERootPoweredItem extends AEBaseItem implements IAEItemPow return this.getInternalBattery( is, batteryOperation.EXTRACT, amt ); } - private double getInternalBattery( ItemStack is, batteryOperation op, double adjustment ) - { - NBTTagCompound data = Platform.openNbtData( is ); - - double currentStorage = data.getDouble( this.POWER_NBT_KEY ); - double maxStorage = this.getAEMaxPower( is ); - - switch ( op ) - { - case INJECT: - currentStorage += adjustment; - if ( currentStorage > maxStorage ) - { - double diff = currentStorage - maxStorage; - data.setDouble( this.POWER_NBT_KEY, maxStorage ); - return diff; - } - data.setDouble( this.POWER_NBT_KEY, currentStorage ); - return 0; - case EXTRACT: - if ( currentStorage > adjustment ) - { - currentStorage -= adjustment; - data.setDouble( this.POWER_NBT_KEY, currentStorage ); - return adjustment; - } - data.setDouble( this.POWER_NBT_KEY, 0 ); - return currentStorage; - default: - break; - } - - return currentStorage; - } - @Override public double getAEMaxPower( ItemStack is ) { @@ -202,5 +200,4 @@ public abstract class AERootPoweredItem extends AEBaseItem implements IAEItemPow { STORAGE, INJECT, EXTRACT } - } diff --git a/src/main/java/appeng/items/tools/powered/powersink/IC2.java b/src/main/java/appeng/items/tools/powered/powersink/IC2.java index 5d9033356..bfb66b1a4 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/IC2.java +++ b/src/main/java/appeng/items/tools/powered/powersink/IC2.java @@ -33,8 +33,7 @@ import appeng.transformer.annotations.Integration.InterfaceList; import appeng.transformer.annotations.Integration.Method; -@InterfaceList( value = { @Interface( iface = "ic2.api.item.ISpecialElectricItem", iname = "IC2" ), - @Interface( iface = "ic2.api.item.IElectricItemManager", iname = "IC2" ) } ) +@InterfaceList( value = { @Interface( iface = "ic2.api.item.ISpecialElectricItem", iname = "IC2" ), @Interface( iface = "ic2.api.item.IElectricItemManager", iname = "IC2" ) } ) public abstract class IC2 extends AERootPoweredItem implements IElectricItemManager, ISpecialElectricItem { public IC2( double powerCapacity, Optional subName ) @@ -48,10 +47,10 @@ public abstract class IC2 extends AERootPoweredItem implements IElectricItemMana double addedAmt = amount; double limit = this.getTransferLimit( is ); - if ( !ignoreTransferLimit && amount > limit ) + if( !ignoreTransferLimit && amount > limit ) addedAmt = limit; - return addedAmt - ( ( int ) this.injectExternalPower( PowerUnits.EU, is, addedAmt, simulate ) ); + return addedAmt - ( (int) this.injectExternalPower( PowerUnits.EU, is, addedAmt, simulate ) ); } @Override @@ -63,7 +62,7 @@ public abstract class IC2 extends AERootPoweredItem implements IElectricItemMana @Override public double getCharge( ItemStack is ) { - return ( int ) PowerUnits.AE.convertTo( PowerUnits.EU, this.getAECurrentPower( is ) ); + return (int) PowerUnits.AE.convertTo( PowerUnits.EU, this.getAECurrentPower( is ) ); } @Override @@ -75,7 +74,7 @@ public abstract class IC2 extends AERootPoweredItem implements IElectricItemMana @Override public boolean use( ItemStack is, double amount, EntityLivingBase entity ) { - if ( this.canUse( is, amount ) ) + if( this.canUse( is, amount ) ) { // use the power.. this.extractAEPower( is, PowerUnits.EU.convertTo( PowerUnits.AE, amount ) ); @@ -138,5 +137,4 @@ public abstract class IC2 extends AERootPoweredItem implements IElectricItemMana { return this; } - } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java index cc1940f21..e07234a52 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java @@ -21,11 +21,11 @@ package appeng.items.tools.quartz; import java.util.EnumSet; -import com.google.common.base.Optional; - import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; +import com.google.common.base.Optional; + import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java index 9f74758f2..6f4e6a5af 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java @@ -54,7 +54,7 @@ public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem @Override public boolean onItemUse( ItemStack is, EntityPlayer p, World w, int x, int y, int z, int s, float hitX, float hitY, float hitZ ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE ); return true; } @@ -62,7 +62,7 @@ public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem @Override public ItemStack onItemRightClick( ItemStack it, World w, EntityPlayer p ) { - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE ); p.swingItem(); return it; @@ -104,5 +104,4 @@ public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem { return new QuartzKnifeObj( is ); } - } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java index 23edeb890..b2be21c9c 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java @@ -21,11 +21,11 @@ package appeng.items.tools.quartz; import java.util.EnumSet; -import com.google.common.base.Optional; - import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemStack; +import com.google.common.base.Optional; + import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java index bdc0cad75..fb0ab81c9 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java @@ -21,11 +21,11 @@ package appeng.items.tools.quartz; import java.util.EnumSet; -import com.google.common.base.Optional; - import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; +import com.google.common.base.Optional; + import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java index d270f9c62..3bbc964b1 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java @@ -21,11 +21,11 @@ package appeng.items.tools.quartz; import java.util.EnumSet; -import com.google.common.base.Optional; - import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; +import com.google.common.base.Optional; + import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java index 7cff6e421..675730f56 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java @@ -21,11 +21,11 @@ package appeng.items.tools.quartz; import java.util.EnumSet; -import com.google.common.base.Optional; - import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; +import com.google.common.base.Optional; + import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java index 084a6ffa7..a2bbdca15 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java @@ -55,13 +55,13 @@ public class ToolQuartzWrench extends AEBaseItem implements IAEWrench, IToolWren public boolean onItemUseFirst( ItemStack is, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ ) { Block b = world.getBlock( x, y, z ); - if ( b != null && !player.isSneaking() && Platform.hasPermissions( new DimensionalCoord( world, x, y, z ), player ) ) + if( b != null && !player.isSneaking() && Platform.hasPermissions( new DimensionalCoord( world, x, y, z ), player ) ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return !world.isRemote; ForgeDirection mySide = ForgeDirection.getOrientation( side ); - if ( b.rotateBlock( world, x, y, z, mySide ) ) + if( b.rotateBlock( world, x, y, z, mySide ) ) { b.onNeighborBlockChange( world, x, y, z, Platform.AIR ); player.swingItem(); @@ -95,5 +95,4 @@ public class ToolQuartzWrench extends AEBaseItem implements IAEWrench, IToolWren { player.swingItem(); } - } diff --git a/src/main/java/appeng/me/Grid.java b/src/main/java/appeng/me/Grid.java index b900693cc..06f987146 100644 --- a/src/main/java/appeng/me/Grid.java +++ b/src/main/java/appeng/me/Grid.java @@ -55,7 +55,7 @@ public class Grid implements IGrid this.pivot = center; Map, IGridCache> myCaches = AEApi.instance().registries().gridCache().createCacheInstance( this ); - for ( Entry, IGridCache> c : myCaches.entrySet() ) + for( Entry, IGridCache> c : myCaches.entrySet() ) { Class key = c.getKey(); IGridCache value = c.getValue(); @@ -94,14 +94,14 @@ public class Grid implements IGrid public int size() { int out = 0; - for ( Collection x : this.machines.values() ) + for( Collection x : this.machines.values() ) out += x.size(); return out; } public void remove( GridNode gridNode ) { - for ( IGridCache c : this.caches.values() ) + for( IGridCache c : this.caches.values() ) { IGridHost machine = gridNode.getMachine(); c.removeNode( gridNode, machine ); @@ -109,16 +109,16 @@ public class Grid implements IGrid Class machineClass = gridNode.getMachineClass(); Set nodes = this.machines.get( machineClass ); - if ( nodes != null ) + if( nodes != null ) nodes.remove( gridNode ); gridNode.setGridStorage( null ); - if ( this.pivot == gridNode ) + if( this.pivot == gridNode ) { Iterator n = this.getNodes().iterator(); - if ( n.hasNext() ) - this.pivot = ( GridNode ) n.next(); + if( n.hasNext() ) + this.pivot = (GridNode) n.next(); else { this.pivot = null; @@ -133,7 +133,7 @@ public class Grid implements IGrid Class mClass = gridNode.getMachineClass(); MachineSet nodes = this.machines.get( mClass ); - if ( nodes == null ) + if( nodes == null ) { nodes = new MachineSet( mClass ); this.machines.put( mClass, nodes ); @@ -141,41 +141,41 @@ public class Grid implements IGrid } // handle loading grid storages. - if ( gridNode.getGridStorage() != null ) + if( gridNode.getGridStorage() != null ) { GridStorage gs = gridNode.getGridStorage(); IGrid grid = gs.getGrid(); - if ( grid == null ) + if( grid == null ) { this.myStorage = gs; this.myStorage.setGrid( this ); - for ( IGridCache gc : this.caches.values() ) + for( IGridCache gc : this.caches.values() ) gc.onJoin( this.myStorage ); } - else if ( grid != this ) + else if( grid != this ) { - if ( this.myStorage == null ) + if( this.myStorage == null ) { this.myStorage = WorldSettings.getInstance().getNewGridStorage(); this.myStorage.setGrid( this ); } IGridStorage tmp = new GridStorage(); - if ( !gs.hasDivided( this.myStorage ) ) + if( !gs.hasDivided( this.myStorage ) ) { gs.addDivided( this.myStorage ); - for ( IGridCache gc : ( ( Grid ) grid ).caches.values() ) + for( IGridCache gc : ( (Grid) grid ).caches.values() ) gc.onSplit( tmp ); - for ( IGridCache gc : this.caches.values() ) + for( IGridCache gc : this.caches.values() ) gc.onJoin( tmp ); } } } - else if ( this.myStorage == null ) + else if( this.myStorage == null ) { this.myStorage = WorldSettings.getInstance().getNewGridStorage(); this.myStorage.setGrid( this ); @@ -187,7 +187,7 @@ public class Grid implements IGrid // track node. nodes.add( gridNode ); - for ( IGridCache cache : this.caches.values() ) + for( IGridCache cache : this.caches.values() ) { IGridHost machine = gridNode.getMachine(); cache.addNode( gridNode, machine ); @@ -201,7 +201,7 @@ public class Grid implements IGrid @SuppressWarnings( "unchecked" ) public C getCache( Class iface ) { - return ( C ) this.caches.get( iface ).myCache; + return (C) this.caches.get( iface ).myCache; } @Override @@ -213,7 +213,7 @@ public class Grid implements IGrid @Override public MENetworkEvent postEventTo( IGridNode node, MENetworkEvent ev ) { - return this.eventBus.postEventTo( this, ( GridNode ) node, ev ); + return this.eventBus.postEventTo( this, (GridNode) node, ev ); } @Override @@ -228,7 +228,7 @@ public class Grid implements IGrid public IMachineSet getMachines( Class c ) { MachineSet s = this.machines.get( c ); - if ( s == null ) + if( s == null ) return new MachineSet( c ); return s; } @@ -258,17 +258,17 @@ public class Grid implements IGrid public void update() { - for ( IGridCache gc : this.caches.values() ) + for( IGridCache gc : this.caches.values() ) { // are there any nodes left? - if ( this.pivot != null ) + if( this.pivot != null ) gc.onUpdateTick(); } } public void saveState() { - for ( IGridCache c : this.caches.values() ) + for( IGridCache c : this.caches.values() ) { c.populateGridStorage( this.myStorage ); } diff --git a/src/main/java/appeng/me/GridAccessException.java b/src/main/java/appeng/me/GridAccessException.java index 86c9b9cdb..6877e2176 100644 --- a/src/main/java/appeng/me/GridAccessException.java +++ b/src/main/java/appeng/me/GridAccessException.java @@ -18,9 +18,9 @@ package appeng.me; + public class GridAccessException extends Exception { private static final long serialVersionUID = 3914554394866375300L; - } diff --git a/src/main/java/appeng/me/GridCacheWrapper.java b/src/main/java/appeng/me/GridCacheWrapper.java index c70d8bcd2..499c3b557 100644 --- a/src/main/java/appeng/me/GridCacheWrapper.java +++ b/src/main/java/appeng/me/GridCacheWrapper.java @@ -18,18 +18,21 @@ package appeng.me; + import appeng.api.networking.IGridCache; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IGridStorage; + public class GridCacheWrapper implements IGridCache { final IGridCache myCache; final String name; - public GridCacheWrapper(final IGridCache gc) { + public GridCacheWrapper( final IGridCache gc ) + { this.myCache = gc; this.name = this.myCache.getClass().getName(); } @@ -41,38 +44,37 @@ public class GridCacheWrapper implements IGridCache } @Override - public void removeNode(final IGridNode gridNode, final IGridHost machine) + public void removeNode( final IGridNode gridNode, final IGridHost machine ) { this.myCache.removeNode( gridNode, machine ); } @Override - public void addNode(final IGridNode gridNode, final IGridHost machine) + public void addNode( final IGridNode gridNode, final IGridHost machine ) { this.myCache.addNode( gridNode, machine ); } + @Override + public void onSplit( final IGridStorage storageB ) + { + this.myCache.onSplit( storageB ); + } + + @Override + public void onJoin( final IGridStorage storageB ) + { + this.myCache.onJoin( storageB ); + } + + @Override + public void populateGridStorage( final IGridStorage storage ) + { + this.myCache.populateGridStorage( storage ); + } + public String getName() { return this.name; } - - @Override - public void onSplit(final IGridStorage storageB) - { - this.myCache.onSplit( storageB ); - } - - @Override - public void onJoin(final IGridStorage storageB) - { - this.myCache.onJoin( storageB ); - } - - @Override - public void populateGridStorage(final IGridStorage storage) - { - this.myCache.populateGridStorage( storage ); - } - } diff --git a/src/main/java/appeng/me/GridConnection.java b/src/main/java/appeng/me/GridConnection.java index 0c79d297d..fedaf7360 100644 --- a/src/main/java/appeng/me/GridConnection.java +++ b/src/main/java/appeng/me/GridConnection.java @@ -44,24 +44,21 @@ public class GridConnection implements IGridConnection, IPathItem { private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); - + public int channelData = 0; + Object visitorIterationNumber = null; private GridNode sideA; private ForgeDirection fromAtoB; private GridNode sideB; - Object visitorIterationNumber = null; - - public int channelData = 0; - public GridConnection( IGridNode aNode, IGridNode bNode, ForgeDirection fromAtoB ) throws FailedConnection { - GridNode a = ( GridNode ) aNode; - GridNode b = ( GridNode ) bNode; + GridNode a = (GridNode) aNode; + GridNode b = (GridNode) bNode; - if ( Platform.securityCheck( a, b ) ) + if( Platform.securityCheck( a, b ) ) { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.LogSecurityAudits ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.LogSecurityAudits ) ) { final DimensionalCoord aCoordinates = a.getGridBlock().getLocation(); final DimensionalCoord bCoordinates = b.getGridBlock().getLocation(); @@ -73,10 +70,10 @@ public class GridConnection implements IGridConnection, IPathItem throw new FailedConnection(); } - if ( a == null || b == null ) + if( a == null || b == null ) throw new GridException( "Connection Forged Between null entities." ); - if ( a.hasConnection( b ) || b.hasConnection( a ) ) + if( a.hasConnection( b ) || b.hasConnection( a ) ) { final String aCoords = a.getGridBlock().getLocation().toString(); final String bCoords = b.getGridBlock().getLocation().toString(); @@ -87,23 +84,23 @@ public class GridConnection implements IGridConnection, IPathItem this.fromAtoB = fromAtoB; this.sideB = b; - if ( b.getMyGrid() == null ) + if( b.getMyGrid() == null ) { b.setGrid( a.getInternalGrid() ); } else { - if ( a.getMyGrid() == null ) + if( a.getMyGrid() == null ) { GridPropagator gp = new GridPropagator( b.getInternalGrid() ); a.beginVisit( gp ); } - else if ( b.getMyGrid() == null ) + else if( b.getMyGrid() == null ) { GridPropagator gp = new GridPropagator( a.getInternalGrid() ); b.beginVisit( gp ); } - else if ( this.isNetworkABetter( a, b ) ) + else if( this.isNetworkABetter( a, b ) ) { GridPropagator gp = new GridPropagator( a.getInternalGrid() ); b.beginVisit( gp ); @@ -128,6 +125,29 @@ public class GridConnection implements IGridConnection, IPathItem return a.getMyGrid().getPriority() > b.getMyGrid().getPriority() || a.getMyGrid().size() > b.getMyGrid().size(); } + @Override + public IGridNode getOtherSide( IGridNode gridNode ) + { + if( gridNode == this.sideA ) + return this.sideB; + if( gridNode == this.sideB ) + return this.sideA; + + throw new GridException( "Invalid Side of Connection" ); + } + + @Override + public ForgeDirection getDirection( IGridNode side ) + { + if( this.fromAtoB == ForgeDirection.UNKNOWN ) + return this.fromAtoB; + + if( this.sideA == side ) + return this.fromAtoB; + else + return this.fromAtoB.getOpposite(); + } + @Override public void destroy() { @@ -148,74 +168,28 @@ public class GridConnection implements IGridConnection, IPathItem return this.sideA; } - @Override - public ForgeDirection getDirection( IGridNode side ) - { - if ( this.fromAtoB == ForgeDirection.UNKNOWN ) - return this.fromAtoB; - - if ( this.sideA == side ) - return this.fromAtoB; - else - return this.fromAtoB.getOpposite(); - } - @Override public IGridNode b() { return this.sideB; } - @Override - public IGridNode getOtherSide( IGridNode gridNode ) - { - if ( gridNode == this.sideA ) - return this.sideB; - if ( gridNode == this.sideB ) - return this.sideA; - - throw new GridException( "Invalid Side of Connection" ); - } - @Override public boolean hasDirection() { return this.fromAtoB != ForgeDirection.UNKNOWN; } - @Override - public IReadOnlyCollection getPossibleOptions() - { - return new ReadOnlyCollection( Arrays.asList( ( IPathItem ) this.a(), ( IPathItem ) this.b() ) ); - } - - @Override - public void incrementChannelCount( int usedChannels ) - { - this.channelData += usedChannels; - } - - @Override - public boolean canSupportMoreChannels() - { - return this.getLastUsedChannels() < 32; // max, PERIOD. - } - @Override public int getUsedChannels() { return ( this.channelData >> 8 ) & 0xff; } - public int getLastUsedChannels() - { - return this.channelData & 0xff; - } - @Override public IPathItem getControllerRoute() { - if ( this.sideA.getFlags().contains( GridFlags.CANNOT_CARRY ) ) + if( this.sideA.getFlags().contains( GridFlags.CANNOT_CARRY ) ) return null; return this.sideA; } @@ -223,10 +197,10 @@ public class GridConnection implements IGridConnection, IPathItem @Override public void setControllerRoute( IPathItem fast, boolean zeroOut ) { - if ( zeroOut ) + if( zeroOut ) this.channelData &= ~0xff; - if ( this.sideB == fast ) + if( this.sideB == fast ) { GridNode tmp = this.sideA; this.sideA = this.sideB; @@ -236,19 +210,21 @@ public class GridConnection implements IGridConnection, IPathItem } @Override - public void finalizeChannels() + public boolean canSupportMoreChannels() { - if ( this.getUsedChannels() != this.getLastUsedChannels() ) - { - this.channelData &= 0xff; - this.channelData |= this.channelData << 8; + return this.getLastUsedChannels() < 32; // max, PERIOD. + } - if ( this.sideA.getInternalGrid() != null ) - this.sideA.getInternalGrid().postEventTo( this.sideA, EVENT ); + @Override + public IReadOnlyCollection getPossibleOptions() + { + return new ReadOnlyCollection( Arrays.asList( (IPathItem) this.a(), (IPathItem) this.b() ) ); + } - if ( this.sideB.getInternalGrid() != null ) - this.sideB.getInternalGrid().postEventTo( this.sideB, EVENT ); - } + @Override + public void incrementChannelCount( int usedChannels ) + { + this.channelData += usedChannels; } @Override @@ -257,4 +233,24 @@ public class GridConnection implements IGridConnection, IPathItem return EnumSet.noneOf( GridFlags.class ); } + @Override + public void finalizeChannels() + { + if( this.getUsedChannels() != this.getLastUsedChannels() ) + { + this.channelData &= 0xff; + this.channelData |= this.channelData << 8; + + if( this.sideA.getInternalGrid() != null ) + this.sideA.getInternalGrid().postEventTo( this.sideA, EVENT ); + + if( this.sideB.getInternalGrid() != null ) + this.sideB.getInternalGrid().postEventTo( this.sideB, EVENT ); + } + } + + public int getLastUsedChannels() + { + return this.channelData & 0xff; + } } diff --git a/src/main/java/appeng/me/GridException.java b/src/main/java/appeng/me/GridException.java index 039619eaf..ad236ee7a 100644 --- a/src/main/java/appeng/me/GridException.java +++ b/src/main/java/appeng/me/GridException.java @@ -18,12 +18,14 @@ package appeng.me; + public class GridException extends RuntimeException { private static final long serialVersionUID = -8110077032108243076L; - public GridException(String s) { + public GridException( String s ) + { super( s ); } diff --git a/src/main/java/appeng/me/GridNode.java b/src/main/java/appeng/me/GridNode.java index d0f17bbdc..727e4ab6a 100644 --- a/src/main/java/appeng/me/GridNode.java +++ b/src/main/java/appeng/me/GridNode.java @@ -101,7 +101,7 @@ public class GridNode implements IGridNode, IPathItem public void addConnection( IGridConnection gridConnection ) { this.connections.add( gridConnection ); - if ( gridConnection.hasDirection() ) + if( gridConnection.hasDirection() ) this.gridProxy.onGridNotification( GridNotification.ConnectionsChanged ); final IGridNode gn = this; @@ -112,15 +112,15 @@ public class GridNode implements IGridNode, IPathItem public void removeConnection( IGridConnection gridConnection ) { this.connections.remove( gridConnection ); - if ( gridConnection.hasDirection() ) + if( gridConnection.hasDirection() ) this.gridProxy.onGridNotification( GridNotification.ConnectionsChanged ); } public boolean hasConnection( IGridNode otherSide ) { - for ( IGridConnection gc : this.connections ) + for( IGridConnection gc : this.connections ) { - if ( gc.a() == otherSide || gc.b() == otherSide ) + if( gc.a() == otherSide || gc.b() == otherSide ) return true; } return false; @@ -130,23 +130,16 @@ public class GridNode implements IGridNode, IPathItem { GridSplitDetector gsd = new GridSplitDetector( this.getInternalGrid().getPivot() ); this.beginVisit( gsd ); - if ( !gsd.pivotFound ) + if( !gsd.pivotFound ) { IGridVisitor gp = new GridPropagator( new Grid( this ) ); this.beginVisit( gp ); } } - @Override - public void setPlayerID( int playerID ) - { - if ( playerID >= 0 ) - this.playerID = playerID; - } - public Grid getInternalGrid() { - if ( this.myGrid == null ) + if( this.myGrid == null ) this.myGrid = new Grid( this ); return this.myGrid; @@ -162,31 +155,31 @@ public class GridNode implements IGridNode, IPathItem this.visitorIterationNumber = tracker; - if ( g instanceof IGridConnectionVisitor ) + if( g instanceof IGridConnectionVisitor ) { LinkedList nextConn = new LinkedList(); - IGridConnectionVisitor gcv = ( IGridConnectionVisitor ) g; + IGridConnectionVisitor gcv = (IGridConnectionVisitor) g; - while ( !nextRun.isEmpty() ) + while( !nextRun.isEmpty() ) { - while ( !nextConn.isEmpty() ) + while( !nextConn.isEmpty() ) gcv.visitConnection( nextConn.poll() ); LinkedList thisRun = nextRun; nextRun = new LinkedList(); - for ( GridNode n : thisRun ) + for( GridNode n : thisRun ) n.visitorConnection( tracker, g, nextRun, nextConn ); } } else { - while ( !nextRun.isEmpty() ) + while( !nextRun.isEmpty() ) { LinkedList thisRun = nextRun; nextRun = new LinkedList(); - for ( GridNode n : thisRun ) + for( GridNode n : thisRun ) n.visitorNode( tracker, g, nextRun ); } } @@ -201,7 +194,7 @@ public class GridNode implements IGridNode, IPathItem this.compressedData |= ( this.gridProxy.getGridColor().ordinal() << 3 ); - for ( ForgeDirection dir : this.gridProxy.getConnectableSides() ) + for( ForgeDirection dir : this.gridProxy.getConnectableSides() ) this.compressedData |= ( 1 << ( dir.ordinal() + 8 ) ); this.FindConnections(); @@ -222,18 +215,18 @@ public class GridNode implements IGridNode, IPathItem public void setGrid( Grid grid ) { - if ( this.myGrid == grid ) + if( this.myGrid == grid ) return; - if ( this.myGrid != null ) + if( this.myGrid != null ) { this.myGrid.remove( this ); - if ( this.myGrid.isEmpty() ) + if( this.myGrid.isEmpty() ) { this.myGrid.saveState(); - for ( IGridCache c : grid.getCaches().values() ) + for( IGridCache c : grid.getCaches().values() ) c.onJoin( this.myGrid.getMyStorage() ); } } @@ -245,19 +238,19 @@ public class GridNode implements IGridNode, IPathItem @Override public void destroy() { - while ( !this.connections.isEmpty() ) + while( !this.connections.isEmpty() ) { // not part of this network for real anymore. - if ( this.connections.size() == 1 ) + if( this.connections.size() == 1 ) this.setGridStorage( null ); IGridConnection c = this.connections.listIterator().next(); - GridNode otherSide = ( GridNode ) c.getOtherSide( this ); + GridNode otherSide = (GridNode) c.getOtherSide( this ); otherSide.getInternalGrid().setPivot( otherSide ); c.destroy(); } - if ( this.myGrid != null ) + if( this.myGrid != null ) this.myGrid.remove( this ); } @@ -271,7 +264,7 @@ public class GridNode implements IGridNode, IPathItem public EnumSet getConnectedSides() { EnumSet set = EnumSet.noneOf( ForgeDirection.class ); - for ( IGridConnection gc : this.connections ) + for( IGridConnection gc : this.connections ) set.add( gc.getDirection( this ) ); return set; } @@ -292,7 +285,7 @@ public class GridNode implements IGridNode, IPathItem public boolean isActive() { IGrid g = this.getGrid(); - if ( g != null ) + if( g != null ) { IPathingGrid pg = g.getCache( IPathingGrid.class ); IEnergyGrid eg = g.getCache( IEnergyGrid.class ); @@ -304,7 +297,7 @@ public class GridNode implements IGridNode, IPathItem @Override public void loadFromNBT( String name, NBTTagCompound nodeData ) { - if ( this.myGrid == null ) + if( this.myGrid == null ) { NBTTagCompound node = nodeData.getCompoundTag( name ); this.playerID = node.getInteger( "p" ); @@ -318,7 +311,7 @@ public class GridNode implements IGridNode, IPathItem @Override public void saveToNBT( String name, NBTTagCompound nodeData ) { - if ( this.myStorage != null ) + if( this.myStorage != null ) { NBTTagCompound node = new NBTTagCompound(); @@ -344,6 +337,19 @@ public class GridNode implements IGridNode, IPathItem return this.gridProxy.getFlags().contains( flag ); } + @Override + public int getPlayerID() + { + return this.playerID; + } + + @Override + public void setPlayerID( int playerID ) + { + if( playerID >= 0 ) + this.playerID = playerID; + } + public int getUsedChannels() { return this.channelData & 0xff; @@ -351,41 +357,41 @@ public class GridNode implements IGridNode, IPathItem public void FindConnections() { - if ( !this.gridProxy.isWorldAccessible() ) + if( !this.gridProxy.isWorldAccessible() ) return; EnumSet newSecurityConnections = EnumSet.noneOf( ForgeDirection.class ); DimensionalCoord dc = this.gridProxy.getLocation(); - for ( ForgeDirection f : ForgeDirection.VALID_DIRECTIONS ) + for( ForgeDirection f : ForgeDirection.VALID_DIRECTIONS ) { IGridHost te = this.findGridHost( dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ ); - if ( te != null ) + if( te != null ) { - GridNode node = ( GridNode ) te.getGridNode( f.getOpposite() ); - if ( node == null ) + GridNode node = (GridNode) te.getGridNode( f.getOpposite() ); + if( node == null ) continue; boolean isValidConnection = this.canConnect( node, f ) && node.canConnect( this, f.getOpposite() ); IGridConnection con = null; // find the connection for this // direction.. - for ( IGridConnection c : this.getConnections() ) + for( IGridConnection c : this.getConnections() ) { - if ( c.getDirection( this ) == f ) + if( c.getDirection( this ) == f ) { con = c; break; } } - if ( con != null ) + if( con != null ) { IGridNode os = con.getOtherSide( this ); - if ( os == node ) + if( os == node ) { // if this connection is no longer valid, destroy it. - if ( !isValidConnection ) + if( !isValidConnection ) con.destroy(); } else @@ -394,9 +400,9 @@ public class GridNode implements IGridNode, IPathItem // throw new GridException( "invalid state found, encountered connection to phantom block." ); } } - else if ( isValidConnection ) + else if( isValidConnection ) { - if ( node.lastSecurityKey != -1 ) + if( node.lastSecurityKey != -1 ) newSecurityConnections.add( f ); else { @@ -405,7 +411,7 @@ public class GridNode implements IGridNode, IPathItem { new GridConnection( node, this, f.getOpposite() ); } - catch ( FailedConnection e ) + catch( FailedConnection e ) { TickHandler.INSTANCE.addCallable( node.getWorld(), new MachineSecurityBreak( this ) ); @@ -416,13 +422,13 @@ public class GridNode implements IGridNode, IPathItem } } - for ( ForgeDirection f : newSecurityConnections ) + for( ForgeDirection f : newSecurityConnections ) { IGridHost te = this.findGridHost( dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ ); - if ( te != null ) + if( te != null ) { - GridNode node = ( GridNode ) te.getGridNode( f.getOpposite() ); - if ( node == null ) + GridNode node = (GridNode) te.getGridNode( f.getOpposite() ); + if( node == null ) continue; // construct a new connection between these two nodes. @@ -430,7 +436,7 @@ public class GridNode implements IGridNode, IPathItem { new GridConnection( node, this, f.getOpposite() ); } - catch ( FailedConnection e ) + catch( FailedConnection e ) { TickHandler.INSTANCE.addCallable( node.getWorld(), new MachineSecurityBreak( this ) ); @@ -442,21 +448,21 @@ public class GridNode implements IGridNode, IPathItem private IGridHost findGridHost( World world, int x, int y, int z ) { - if ( world.blockExists( x, y, z ) ) + if( world.blockExists( x, y, z ) ) { TileEntity te = world.getTileEntity( x, y, z ); - if ( te instanceof IGridHost ) - return ( IGridHost ) te; + if( te instanceof IGridHost ) + return (IGridHost) te; } return null; } public boolean canConnect( GridNode from, ForgeDirection dir ) { - if ( !this.isValidDirection( dir ) ) + if( !this.isValidDirection( dir ) ) return false; - if ( !from.getColor().matches( this.getColor() ) ) + if( !from.getColor().matches( this.getColor() ) ) return false; return true; @@ -474,20 +480,20 @@ public class GridNode implements IGridNode, IPathItem private void visitorConnection( Object tracker, IGridVisitor g, Deque nextRun, Deque nextConnections ) { - if ( g.visitNode( this ) ) + if( g.visitNode( this ) ) { - for ( IGridConnection gc : this.getConnections() ) + for( IGridConnection gc : this.getConnections() ) { - GridNode gn = ( GridNode ) gc.getOtherSide( this ); - GridConnection gcc = ( GridConnection ) gc; + GridNode gn = (GridNode) gc.getOtherSide( this ); + GridConnection gcc = (GridConnection) gc; - if ( gcc.visitorIterationNumber != tracker ) + if( gcc.visitorIterationNumber != tracker ) { gcc.visitorIterationNumber = tracker; nextConnections.add( gc ); } - if ( tracker == gn.visitorIterationNumber ) + if( tracker == gn.visitorIterationNumber ) continue; gn.visitorIterationNumber = tracker; @@ -499,13 +505,13 @@ public class GridNode implements IGridNode, IPathItem private void visitorNode( Object tracker, IGridVisitor g, Deque nextRun ) { - if ( g.visitNode( this ) ) + if( g.visitNode( this ) ) { - for ( IGridConnection gc : this.getConnections() ) + for( IGridConnection gc : this.getConnections() ) { - GridNode gn = ( GridNode ) gc.getOtherSide( this ); + GridNode gn = (GridNode) gc.getOtherSide( this ); - if ( tracker == gn.visitorIterationNumber ) + if( tracker == gn.visitorIterationNumber ) continue; gn.visitorIterationNumber = tracker; @@ -529,23 +535,23 @@ public class GridNode implements IGridNode, IPathItem @Override public IPathItem getControllerRoute() { - if ( this.connections.isEmpty() || this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) + if( this.connections.isEmpty() || this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) return null; - return ( IPathItem ) this.connections.get( 0 ); + return (IPathItem) this.connections.get( 0 ); } @Override public void setControllerRoute( IPathItem fast, boolean zeroOut ) { - if ( zeroOut ) + if( zeroOut ) this.channelData &= ~0xff; int idx = this.connections.indexOf( fast ); - if ( idx > 0 ) + if( idx > 0 ) { this.connections.remove( fast ); - this.connections.add( 0, ( IGridConnection ) fast ); + this.connections.add( 0, (IGridConnection) fast ); } } @@ -563,7 +569,7 @@ public class GridNode implements IGridNode, IPathItem @Override public IReadOnlyCollection getPossibleOptions() { - return ( ReadOnlyCollection ) this.getConnections(); + return (ReadOnlyCollection) this.getConnections(); } @Override @@ -581,15 +587,15 @@ public class GridNode implements IGridNode, IPathItem @Override public void finalizeChannels() { - if ( this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) + if( this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) return; - if ( this.getLastUsedChannels() != this.getUsedChannels() ) + if( this.getLastUsedChannels() != this.getUsedChannels() ) { this.channelData &= 0xff; this.channelData |= this.channelData << 8; - if ( this.getInternalGrid() != null ) + if( this.getInternalGrid() != null ) this.getInternalGrid().postEventTo( this, EVENT ); } } @@ -636,10 +642,4 @@ public class GridNode implements IGridNode, IPathItem return preferredA == preferredB ? 0 : ( preferredA ? -1 : 1 ); } } - - @Override - public int getPlayerID() - { - return this.playerID; - } } diff --git a/src/main/java/appeng/me/GridNodeCollection.java b/src/main/java/appeng/me/GridNodeCollection.java index 8b7e86982..7dde8dcd1 100644 --- a/src/main/java/appeng/me/GridNodeCollection.java +++ b/src/main/java/appeng/me/GridNodeCollection.java @@ -48,7 +48,7 @@ public class GridNodeCollection implements IReadOnlyCollection { int size = 0; - for ( Set o : this.machines.values() ) + for( Set o : this.machines.values() ) size += o.size(); return size; @@ -57,8 +57,8 @@ public class GridNodeCollection implements IReadOnlyCollection @Override public boolean isEmpty() { - for ( Set o : this.machines.values() ) - if ( !o.isEmpty() ) + for( Set o : this.machines.values() ) + if( !o.isEmpty() ) return false; return true; @@ -69,9 +69,9 @@ public class GridNodeCollection implements IReadOnlyCollection { final boolean doesContainNode; - if ( maybeGridNode instanceof IGridNode ) + if( maybeGridNode instanceof IGridNode ) { - final IGridNode node = ( IGridNode ) maybeGridNode; + final IGridNode node = (IGridNode) maybeGridNode; IGridHost machine = node.getMachine(); Class machineClass = machine.getClass(); diff --git a/src/main/java/appeng/me/GridNodeIterator.java b/src/main/java/appeng/me/GridNodeIterator.java index 7921da4fc..ede346004 100644 --- a/src/main/java/appeng/me/GridNodeIterator.java +++ b/src/main/java/appeng/me/GridNodeIterator.java @@ -47,7 +47,7 @@ public class GridNodeIterator implements Iterator { final boolean hasNext = this.outerIterator.hasNext(); - if ( hasNext ) + if( hasNext ) { final MachineSet nextElem = this.outerIterator.next(); this.innerIterator = nextElem.iterator(); @@ -59,13 +59,13 @@ public class GridNodeIterator implements Iterator @Override public boolean hasNext() { - while ( true ) + while( true ) { - if ( this.innerIterator.hasNext() ) + if( this.innerIterator.hasNext() ) { return true; } - else if ( !this.innerHasNext() ) + else if( !this.innerHasNext() ) { return false; } diff --git a/src/main/java/appeng/me/GridPropagator.java b/src/main/java/appeng/me/GridPropagator.java index c86556b0a..e14d51995 100644 --- a/src/main/java/appeng/me/GridPropagator.java +++ b/src/main/java/appeng/me/GridPropagator.java @@ -35,8 +35,8 @@ public class GridPropagator implements IGridVisitor @Override public boolean visitNode( IGridNode n ) { - GridNode gn = ( GridNode ) n; - if ( gn.getMyGrid() != this.g || this.g.getPivot() == n ) + GridNode gn = (GridNode) n; + if( gn.getMyGrid() != this.g || this.g.getPivot() == n ) { gn.setGrid( this.g ); diff --git a/src/main/java/appeng/me/GridSplitDetector.java b/src/main/java/appeng/me/GridSplitDetector.java index 3d7391a86..f84cceb84 100644 --- a/src/main/java/appeng/me/GridSplitDetector.java +++ b/src/main/java/appeng/me/GridSplitDetector.java @@ -18,23 +18,26 @@ package appeng.me; + import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; + class GridSplitDetector implements IGridVisitor { final IGridNode pivot; boolean pivotFound; - public GridSplitDetector(IGridNode pivot) { + public GridSplitDetector( IGridNode pivot ) + { this.pivot = pivot; } @Override - public boolean visitNode(IGridNode n) + public boolean visitNode( IGridNode n ) { - if ( n == this.pivot ) + if( n == this.pivot ) this.pivotFound = true; return !this.pivotFound; diff --git a/src/main/java/appeng/me/GridStorage.java b/src/main/java/appeng/me/GridStorage.java index 1858b3194..e7262fce7 100644 --- a/src/main/java/appeng/me/GridStorage.java +++ b/src/main/java/appeng/me/GridStorage.java @@ -18,6 +18,7 @@ package appeng.me; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -32,26 +33,26 @@ import appeng.api.networking.IGridStorage; import appeng.core.AELog; import appeng.core.WorldSettings; + public class GridStorage implements IGridStorage { - private WeakReference internalGrid = null; - final long myID; final NBTTagCompound data; - - public boolean isDirty = false; - private final WeakHashMap divided = new WeakHashMap(); final GridStorageSearch mySearchEntry; // keep myself in the list until I'm - // lost... + private final WeakHashMap divided = new WeakHashMap(); + public boolean isDirty = false; + private WeakReference internalGrid = null; + // lost... /** * for use with world settings * - * @param id ID of grid storage + * @param id ID of grid storage * @param gss grid storage search */ - public GridStorage(long id, GridStorageSearch gss) { + public GridStorage( long id, GridStorageSearch gss ) + { this.myID = id; this.mySearchEntry = gss; this.data = new NBTTagCompound(); @@ -61,10 +62,11 @@ public class GridStorage implements IGridStorage * for use with world settings * * @param input array of bytes string - * @param id ID of grid storage - * @param gss grid storage search + * @param id ID of grid storage + * @param gss grid storage search */ - public GridStorage(String input, long id, GridStorageSearch gss) { + public GridStorage( String input, long id, GridStorageSearch gss ) + { this.myID = id; this.mySearchEntry = gss; NBTTagCompound myTag = null; @@ -74,7 +76,7 @@ public class GridStorage implements IGridStorage byte[] byteData = javax.xml.bind.DatatypeConverter.parseBase64Binary( input ); myTag = CompressedStreamTools.readCompressed( new ByteArrayInputStream( byteData ) ); } - catch (Throwable t) + catch( Throwable t ) { myTag = new NBTTagCompound(); } @@ -85,7 +87,8 @@ public class GridStorage implements IGridStorage /** * fake storage. */ - public GridStorage() { + public GridStorage() + { this.myID = 0; this.mySearchEntry = null; this.data = new NBTTagCompound(); @@ -96,7 +99,7 @@ public class GridStorage implements IGridStorage this.isDirty = false; Grid currentGrid = (Grid) this.getGrid(); - if ( currentGrid != null ) + if( currentGrid != null ) { currentGrid.saveState(); } @@ -107,7 +110,7 @@ public class GridStorage implements IGridStorage CompressedStreamTools.writeCompressed( this.data, out ); return javax.xml.bind.DatatypeConverter.printBase64Binary( out.toByteArray() ); } - catch (IOException e) + catch( IOException e ) { AELog.error( e ); } @@ -115,6 +118,16 @@ public class GridStorage implements IGridStorage return ""; } + public IGrid getGrid() + { + return this.internalGrid == null ? null : this.internalGrid.get(); + } + + public void setGrid( Grid grid ) + { + this.internalGrid = new WeakReference( grid ); + } + @Override public NBTTagCompound dataObject() { @@ -132,22 +145,12 @@ public class GridStorage implements IGridStorage this.isDirty = true; } - public IGrid getGrid() - { - return this.internalGrid == null ? null : this.internalGrid.get(); - } - - public void setGrid(Grid grid) - { - this.internalGrid = new WeakReference( grid ); - } - - public void addDivided(GridStorage gs) + public void addDivided( GridStorage gs ) { this.divided.put( gs, true ); } - public boolean hasDivided(GridStorage myStorage) + public boolean hasDivided( GridStorage myStorage ) { return this.divided.containsKey( myStorage ); } @@ -156,5 +159,4 @@ public class GridStorage implements IGridStorage { WorldSettings.getInstance().destroyGridStorage( this.myID ); } - } diff --git a/src/main/java/appeng/me/GridStorageSearch.java b/src/main/java/appeng/me/GridStorageSearch.java index 85da4d0bd..b7e6420a9 100644 --- a/src/main/java/appeng/me/GridStorageSearch.java +++ b/src/main/java/appeng/me/GridStorageSearch.java @@ -18,8 +18,10 @@ package appeng.me; + import java.lang.ref.WeakReference; + public class GridStorageSearch { @@ -31,29 +33,29 @@ public class GridStorageSearch * * @param id ID of grid storage search */ - public GridStorageSearch(long id) { - this.id = id; - } - - @Override - public boolean equals(Object obj) + public GridStorageSearch( long id ) { - if ( obj == null ) - return false; - if ( this.getClass() != obj.getClass() ) - return false; - - GridStorageSearch other = (GridStorageSearch) obj; - if ( this.id == other.id ) - return true; - - return false; + this.id = id; } @Override public int hashCode() { - return ((Long) this.id).hashCode(); + return ( (Long) this.id ).hashCode(); } + @Override + public boolean equals( Object obj ) + { + if( obj == null ) + return false; + if( this.getClass() != obj.getClass() ) + return false; + + GridStorageSearch other = (GridStorageSearch) obj; + if( this.id == other.id ) + return true; + + return false; + } } diff --git a/src/main/java/appeng/me/MachineSet.java b/src/main/java/appeng/me/MachineSet.java index 0ea3e43a5..8f2f56c6d 100644 --- a/src/main/java/appeng/me/MachineSet.java +++ b/src/main/java/appeng/me/MachineSet.java @@ -18,12 +18,14 @@ package appeng.me; + import java.util.HashSet; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IMachineSet; + public class MachineSet extends HashSet implements IMachineSet { @@ -31,7 +33,8 @@ public class MachineSet extends HashSet implements IMachineSet private final Class machine; - MachineSet(Class m) { + MachineSet( Class m ) + { this.machine = m; } @@ -40,5 +43,4 @@ public class MachineSet extends HashSet implements IMachineSet { return this.machine; } - } diff --git a/src/main/java/appeng/me/NetworkEventBus.java b/src/main/java/appeng/me/NetworkEventBus.java index 5b7708789..dc2269f01 100644 --- a/src/main/java/appeng/me/NetworkEventBus.java +++ b/src/main/java/appeng/me/NetworkEventBus.java @@ -41,29 +41,29 @@ public class NetworkEventBus public void readClass( Class listAs, Class c ) { - if ( READ_CLASSES.contains( c ) ) + if( READ_CLASSES.contains( c ) ) return; READ_CLASSES.add( c ); try { - for ( Method m : c.getMethods() ) + for( Method m : c.getMethods() ) { MENetworkEventSubscribe s = m.getAnnotation( MENetworkEventSubscribe.class ); - if ( s != null ) + if( s != null ) { Class[] types = m.getParameterTypes(); - if ( types.length == 1 ) + if( types.length == 1 ) { - if ( MENetworkEvent.class.isAssignableFrom( types[0] ) ) + if( MENetworkEvent.class.isAssignableFrom( types[0] ) ) { Map classEvents = EVENTS.get( types[0] ); - if ( classEvents == null ) + if( classEvents == null ) EVENTS.put( types[0], classEvents = new HashMap() ); MENetworkEventInfo thisEvent = classEvents.get( listAs ); - if ( thisEvent == null ) + if( thisEvent == null ) thisEvent = new MENetworkEventInfo(); thisEvent.Add( types[0], c, m ); @@ -78,7 +78,7 @@ public class NetworkEventBus } } } - catch ( Throwable t ) + catch( Throwable t ) { throw new RuntimeException( "Error while adding " + c.getName() + " to event bus", t ); } @@ -91,19 +91,19 @@ public class NetworkEventBus try { - if ( subscribers != null ) + if( subscribers != null ) { - for ( Entry subscriber : subscribers.entrySet() ) + for( Entry subscriber : subscribers.entrySet() ) { MENetworkEventInfo target = subscriber.getValue(); GridCacheWrapper cache = g.getCaches().get( subscriber.getKey() ); - if ( cache != null ) + if( cache != null ) { x++; target.invoke( cache.myCache, e ); } - for ( IGridNode obj : g.getMachines( subscriber.getKey() ) ) + for( IGridNode obj : g.getMachines( subscriber.getKey() ) ) { x++; target.invoke( obj.getMachine(), e ); @@ -111,7 +111,7 @@ public class NetworkEventBus } } } - catch ( NetworkEventDone done ) + catch( NetworkEventDone done ) { // Early out. } @@ -127,17 +127,17 @@ public class NetworkEventBus try { - if ( subscribers != null ) + if( subscribers != null ) { MENetworkEventInfo target = subscribers.get( node.getMachineClass() ); - if ( target != null ) + if( target != null ) { x++; target.invoke( node.getMachine(), e ); } } } - catch ( NetworkEventDone done ) + catch( NetworkEventDone done ) { // Early out. } @@ -173,7 +173,7 @@ public class NetworkEventBus { this.objMethod.invoke( obj, e ); } - catch ( Throwable e1 ) + catch( Throwable e1 ) { AELog.severe( "[AppEng] Network Event caused exception:" ); AELog.severe( "Offending Class: " + obj.getClass().getName() ); @@ -182,7 +182,7 @@ public class NetworkEventBus throw new RuntimeException( e1 ); } - if ( e.isCanceled() ) + if( e.isCanceled() ) throw new NetworkEventDone(); } } @@ -200,7 +200,7 @@ public class NetworkEventBus public void invoke( Object obj, MENetworkEvent e ) throws NetworkEventDone { - for ( EventMethod em : this.methods ) + for( EventMethod em : this.methods ) em.invoke( obj, e ); } } diff --git a/src/main/java/appeng/me/NetworkList.java b/src/main/java/appeng/me/NetworkList.java index 4d8b43dee..95a01255f 100644 --- a/src/main/java/appeng/me/NetworkList.java +++ b/src/main/java/appeng/me/NetworkList.java @@ -18,46 +18,22 @@ package appeng.me; + import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; + public class NetworkList implements Collection { private List networks = new LinkedList(); @Override - public boolean add(Grid e) + public int size() { - this.copy(); - return this.networks.add( e ); - } - - @Override - public boolean addAll(Collection c) - { - this.copy(); - return this.networks.addAll( c ); - } - - @Override - public void clear() - { - this.networks = new LinkedList(); - } - - @Override - public boolean contains(Object o) - { - return this.networks.contains( o ); - } - - @Override - public boolean containsAll(Collection c) - { - return this.networks.containsAll( c ); + return this.networks.size(); } @Override @@ -66,46 +42,18 @@ public class NetworkList implements Collection return this.networks.isEmpty(); } + @Override + public boolean contains( Object o ) + { + return this.networks.contains( o ); + } + @Override public Iterator iterator() { return this.networks.iterator(); } - @Override - public boolean remove(Object o) - { - this.copy(); - return this.networks.remove( o ); - } - - @Override - public boolean removeAll(Collection c) - { - this.copy(); - return this.networks.removeAll( c ); - } - - @Override - public boolean retainAll(Collection c) - { - this.copy(); - return this.networks.retainAll( c ); - } - - private void copy() - { - List old = this.networks; - this.networks = new LinkedList(); - this.networks.addAll( old ); - } - - @Override - public int size() - { - return this.networks.size(); - } - @Override public Object[] toArray() { @@ -113,9 +61,62 @@ public class NetworkList implements Collection } @Override - public T[] toArray(T[] a) + public T[] toArray( T[] a ) { return this.networks.toArray( a ); } + @Override + public boolean add( Grid e ) + { + this.copy(); + return this.networks.add( e ); + } + + @Override + public boolean remove( Object o ) + { + this.copy(); + return this.networks.remove( o ); + } + + @Override + public boolean containsAll( Collection c ) + { + return this.networks.containsAll( c ); + } + + @Override + public boolean addAll( Collection c ) + { + this.copy(); + return this.networks.addAll( c ); + } + + @Override + public boolean removeAll( Collection c ) + { + this.copy(); + return this.networks.removeAll( c ); + } + + @Override + public boolean retainAll( Collection c ) + { + this.copy(); + return this.networks.retainAll( c ); + } + + @Override + public void clear() + { + this.networks = new LinkedList(); + } + + private void copy() + { + List old = this.networks; + this.networks = new LinkedList(); + this.networks.addAll( old ); + } } diff --git a/src/main/java/appeng/me/cache/CraftingGridCache.java b/src/main/java/appeng/me/cache/CraftingGridCache.java index 57a562a08..7678dcfd7 100644 --- a/src/main/java/appeng/me/cache/CraftingGridCache.java +++ b/src/main/java/appeng/me/cache/CraftingGridCache.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -35,14 +36,14 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; +import net.minecraft.world.World; + import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; -import net.minecraft.world.World; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.IGrid; @@ -84,26 +85,532 @@ import appeng.tile.crafting.TileCraftingStorageTile; import appeng.tile.crafting.TileCraftingTile; import appeng.util.ItemSorters; + public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper, ICellProvider, IMEInventoryHandler { + final public static ExecutorService CRAFTING_POOL; + static final Comparator COMPARATOR = new Comparator() + { + @Override + public int compare( ICraftingPatternDetails firstDetail, ICraftingPatternDetails nextDetail ) + { + return nextDetail.getPriority() - firstDetail.getPriority(); + } + }; + + static + { + ThreadFactory factory = new ThreadFactory() + { + + @Override + public Thread newThread( Runnable ar ) + { + return new Thread( ar, "AE Crafting Calculator" ); + } + }; + + CRAFTING_POOL = Executors.newCachedThreadPool( factory ); + } + private final Set craftingCPUClusters = new HashSet(); private final Set craftingProviders = new HashSet(); - private final Map craftingWatchers = new HashMap(); - private final IGrid grid; - private IStorageGrid storageGrid; - private IEnergyGrid energyGrid; - private final Map> craftingMethods = new HashMap>(); private final Map> craftableItems = new HashMap>(); private final Set emitableItems = new HashSet(); private final Map craftingLinks = new HashMap(); - - private boolean updateList = false; private final Multimap interests = HashMultimap.create(); public final GenericInterestManager interestManager = new GenericInterestManager( this.interests ); + private IStorageGrid storageGrid; + private IEnergyGrid energyGrid; + private boolean updateList = false; + + public CraftingGridCache( IGrid grid ) + { + this.grid = grid; + } + + @MENetworkEventSubscribe + public void afterCacheConstruction( MENetworkPostCacheConstruction cacheConstruction ) + { + this.storageGrid = this.grid.getCache( IStorageGrid.class ); + this.energyGrid = this.grid.getCache( IEnergyGrid.class ); + + this.storageGrid.registerCellProvider( this ); + } + + @Override + public void onUpdateTick() + { + if( this.updateList ) + { + this.updateList = false; + this.updateCPUClusters(); + } + + Iterator craftingLinkIterator = this.craftingLinks.values().iterator(); + while( craftingLinkIterator.hasNext() ) + { + if( craftingLinkIterator.next().isDead( this.grid, this ) ) + { + craftingLinkIterator.remove(); + } + } + + for( CraftingCPUCluster cpu : this.craftingCPUClusters ) + { + cpu.updateCraftingLogic( this.grid, this.energyGrid, this ); + } + } + + @Override + public void removeNode( IGridNode gridNode, IGridHost machine ) + { + if( machine instanceof ICraftingWatcherHost ) + { + ICraftingWatcher craftingWatcher = this.craftingWatchers.get( machine ); + if( craftingWatcher != null ) + { + craftingWatcher.clear(); + this.craftingWatchers.remove( machine ); + } + } + + if( machine instanceof ICraftingRequester ) + { + for( CraftingLinkNexus link : this.craftingLinks.values() ) + { + if( link.isMachine( machine ) ) + { + link.removeNode(); + } + } + } + + if( machine instanceof TileCraftingTile ) + { + this.updateList = true; + } + + if( machine instanceof ICraftingProvider ) + { + this.craftingProviders.remove( machine ); + this.updatePatterns(); + } + } + + @Override + public void addNode( IGridNode gridNode, IGridHost machine ) + { + if( machine instanceof ICraftingWatcherHost ) + { + ICraftingWatcherHost watcherHost = (ICraftingWatcherHost) machine; + CraftingWatcher watcher = new CraftingWatcher( this, watcherHost ); + this.craftingWatchers.put( gridNode, watcher ); + watcherHost.updateWatcher( watcher ); + } + + if( machine instanceof ICraftingRequester ) + { + for( ICraftingLink link : ( (ICraftingRequester) machine ).getRequestedJobs() ) + { + if( link instanceof CraftingLink ) + { + this.addLink( (CraftingLink) link ); + } + } + } + + if( machine instanceof TileCraftingTile ) + { + this.updateList = true; + } + + if( machine instanceof ICraftingProvider ) + { + this.craftingProviders.add( (ICraftingProvider) machine ); + this.updatePatterns(); + } + } + + @Override + public void onSplit( IGridStorage destinationStorage ) + { // nothing! + } + + @Override + public void onJoin( IGridStorage sourceStorage ) + { + // nothing! + } + + @Override + public void populateGridStorage( IGridStorage destinationStorage ) + { + // nothing! + } + + private void updatePatterns() + { + Map> oldItems = this.craftableItems; + + // erase list. + this.craftingMethods.clear(); + this.craftableItems.clear(); + this.emitableItems.clear(); + + // update the stuff that was in the list... + this.storageGrid.postAlterationOfStoredItems( StorageChannel.ITEMS, oldItems.keySet(), new BaseActionSource() ); + + // re-create list.. + for( ICraftingProvider provider : this.craftingProviders ) + { + provider.provideCrafting( this ); + } + + Map> tmpCraft = new HashMap>(); + + // new craftables! + for( ICraftingPatternDetails details : this.craftingMethods.keySet() ) + { + for( IAEItemStack out : details.getOutputs() ) + { + out = out.copy(); + out.reset(); + out.setCraftable( true ); + + Set methods = tmpCraft.get( out ); + + if( methods == null ) + { + tmpCraft.put( out, methods = new TreeSet( COMPARATOR ) ); + } + + methods.add( details ); + } + } + + // make them immutable + for( Entry> e : tmpCraft.entrySet() ) + { + this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) ); + } + + this.storageGrid.postAlterationOfStoredItems( StorageChannel.ITEMS, this.craftableItems.keySet(), new BaseActionSource() ); + } + + private void updateCPUClusters() + { + this.craftingCPUClusters.clear(); + + for( IGridNode cst : this.grid.getMachines( TileCraftingStorageTile.class ) ) + { + TileCraftingStorageTile tile = (TileCraftingStorageTile) cst.getMachine(); + CraftingCPUCluster cluster = (CraftingCPUCluster) tile.getCluster(); + if( cluster != null ) + { + this.craftingCPUClusters.add( cluster ); + + if( cluster.myLastLink != null ) + { + this.addLink( (CraftingLink) cluster.myLastLink ); + } + } + } + } + + public void addLink( CraftingLink link ) + { + if( link.isStandalone() ) + { + return; + } + + CraftingLinkNexus nexus = this.craftingLinks.get( link.getCraftingID() ); + if( nexus == null ) + { + this.craftingLinks.put( link.getCraftingID(), nexus = new CraftingLinkNexus( link.getCraftingID() ) ); + } + + link.setNexus( nexus ); + } + + @MENetworkEventSubscribe + public void updateCPUClusters( MENetworkCraftingCpuChange c ) + { + this.updateList = true; + } + + @MENetworkEventSubscribe + public void updateCPUClusters( MENetworkCraftingPatternChange c ) + { + this.updatePatterns(); + } + + @Override + public void addCraftingOption( ICraftingMedium medium, ICraftingPatternDetails api ) + { + List details = this.craftingMethods.get( api ); + if( details == null ) + { + details = new ArrayList(); + details.add( medium ); + this.craftingMethods.put( api, details ); + } + else + { + details.add( medium ); + } + } + + @Override + public void setEmitable( IAEItemStack someItem ) + { + this.emitableItems.add( someItem.copy() ); + } + + @Override + public List getCellArray( StorageChannel channel ) + { + List list = new ArrayList( 1 ); + + if( channel == StorageChannel.ITEMS ) + { + list.add( this ); + } + + return list; + } + + @Override + public int getPriority() + { + return Integer.MAX_VALUE; + } + + @Override + public AccessRestriction getAccess() + { + return AccessRestriction.WRITE; + } + + @Override + public boolean isPrioritized( IAEStack input ) + { + return true; + } + + @Override + public boolean canAccept( IAEStack input ) + { + for( CraftingCPUCluster cpu : this.craftingCPUClusters ) + { + if( cpu.canAccept( input ) ) + { + return true; + } + } + + return false; + } + + @Override + public int getSlot() + { + return 0; + } + + @Override + public boolean validForPass( int i ) + { + return i == 1; + } + + @Override + public IAEStack injectItems( IAEStack input, Actionable type, BaseActionSource src ) + { + for( CraftingCPUCluster cpu : this.craftingCPUClusters ) + { + input = cpu.injectItems( input, type, src ); + } + + return input; + } + + @Override + public IAEStack extractItems( IAEStack request, Actionable mode, BaseActionSource src ) + { + return null; + } + + @Override + public IItemList getAvailableItems( IItemList out ) + { + // add craftable items! + for( IAEItemStack stack : this.craftableItems.keySet() ) + { + out.addCrafting( stack ); + } + + for( IAEItemStack st : this.emitableItems ) + { + out.addCrafting( st ); + } + + return out; + } + + @Override + public StorageChannel getChannel() + { + return StorageChannel.ITEMS; + } + + @Override + public ImmutableCollection getCraftingFor( IAEItemStack whatToCraft, ICraftingPatternDetails details, int slotIndex, World world ) + { + ImmutableList res = this.craftableItems.get( whatToCraft ); + + if( res == null ) + { + if( details != null && details.isCraftable() ) + { + for( IAEItemStack ais : this.craftableItems.keySet() ) + { + if( ais.getItem() == whatToCraft.getItem() && ( !ais.getItem().getHasSubtypes() || ais.getItemDamage() == whatToCraft.getItemDamage() ) ) + { + if( details.isValidItemForSlot( slotIndex, ais.getItemStack(), world ) ) + { + return this.craftableItems.get( ais ); + } + } + } + } + + return ImmutableSet.of(); + } + + return res; + } + + @Override + public Future beginCraftingJob( World world, IGrid grid, BaseActionSource actionSrc, IAEItemStack slotItem, ICraftingCallback cb ) + { + if( world == null || grid == null || actionSrc == null || slotItem == null ) + { + throw new RuntimeException( "Invalid Crafting Job Request" ); + } + + CraftingJob job = new CraftingJob( world, grid, actionSrc, slotItem, cb ); + + return CRAFTING_POOL.submit( job, (ICraftingJob) job ); + } + + @Override + public ICraftingLink submitJob( ICraftingJob job, ICraftingRequester requestingMachine, ICraftingCPU target, final boolean prioritizePower, BaseActionSource src ) + { + if( job.isSimulation() ) + { + return null; + } + + CraftingCPUCluster cpuCluster = null; + + if( target instanceof CraftingCPUCluster ) + { + cpuCluster = (CraftingCPUCluster) target; + } + + if( target == null ) + { + List validCpusClusters = new ArrayList(); + for( CraftingCPUCluster cpu : this.craftingCPUClusters ) + { + if( cpu.isActive() && !cpu.isBusy() && cpu.getAvailableStorage() >= job.getByteTotal() ) + { + validCpusClusters.add( cpu ); + } + } + + Collections.sort( validCpusClusters, new Comparator() + { + @Override + public int compare( CraftingCPUCluster firstCluster, CraftingCPUCluster nextCluster ) + { + if( prioritizePower ) + { + int comparison = ItemSorters.compareLong( nextCluster.getCoProcessors(), firstCluster.getCoProcessors() ); + if( comparison != 0 ) + return comparison; + return ItemSorters.compareLong( nextCluster.getAvailableStorage(), firstCluster.getAvailableStorage() ); + } + + int comparison = ItemSorters.compareLong( firstCluster.getCoProcessors(), nextCluster.getCoProcessors() ); + if( comparison != 0 ) + return comparison; + return ItemSorters.compareLong( firstCluster.getAvailableStorage(), nextCluster.getAvailableStorage() ); + } + } ); + + if( !validCpusClusters.isEmpty() ) + { + cpuCluster = validCpusClusters.get( 0 ); + } + } + + if( cpuCluster != null ) + { + return cpuCluster.submitJob( this.grid, job, src, requestingMachine ); + } + + return null; + } + + @Override + public ImmutableSet getCpus() + { + return ImmutableSet.copyOf( new ActiveCpuIterator( this.craftingCPUClusters ) ); + } + + @Override + public boolean canEmitFor( IAEItemStack someItem ) + { + return this.emitableItems.contains( someItem ); + } + + @Override + public boolean isRequesting( IAEItemStack what ) + { + for( CraftingCPUCluster cluster : this.craftingCPUClusters ) + { + if( cluster.isMaking( what ) ) + { + return true; + } + } + + return false; + } + + public List getMediums( ICraftingPatternDetails key ) + { + List mediums = this.craftingMethods.get( key ); + + if( mediums == null ) + { + mediums = ImmutableList.of(); + } + + return mediums; + } + + public boolean hasCpu( ICraftingCPU cpu ) + { + return this.craftingCPUClusters.contains( cpu ); + } static class ActiveCpuIterator implements Iterator { @@ -111,7 +618,7 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper private final Iterator iterator; private CraftingCPUCluster cpuCluster; - public ActiveCpuIterator(Collection o) + public ActiveCpuIterator( Collection o ) { this.iterator = o.iterator(); this.cpuCluster = null; @@ -127,10 +634,10 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper private void findNext() { - while (this.iterator.hasNext() && this.cpuCluster == null) + while( this.iterator.hasNext() && this.cpuCluster == null ) { this.cpuCluster = this.iterator.next(); - if ( !this.cpuCluster.isActive() || this.cpuCluster.isDestroyed ) + if( !this.cpuCluster.isActive() || this.cpuCluster.isDestroyed ) { this.cpuCluster = null; } @@ -151,518 +658,5 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper { // no.. } - } - - @Override - public ImmutableSet getCpus() - { - return ImmutableSet.copyOf( new ActiveCpuIterator( this.craftingCPUClusters ) ); - } - - public CraftingGridCache(IGrid grid) - { - this.grid = grid; - } - - @MENetworkEventSubscribe - public void afterCacheConstruction(MENetworkPostCacheConstruction cacheConstruction) - { - this.storageGrid = this.grid.getCache( IStorageGrid.class ); - this.energyGrid = this.grid.getCache( IEnergyGrid.class ); - - this.storageGrid.registerCellProvider( this ); - } - - public void addLink(CraftingLink link) - { - if ( link.isStandalone() ) - { - return; - } - - CraftingLinkNexus nexus = this.craftingLinks.get( link.getCraftingID() ); - if ( nexus == null ) - { - this.craftingLinks.put( link.getCraftingID(), nexus = new CraftingLinkNexus( link.getCraftingID() ) ); - } - - link.setNexus( nexus ); - } - - @Override - public void onUpdateTick() - { - if ( this.updateList ) - { - this.updateList = false; - this.updateCPUClusters(); - } - - Iterator craftingLinkIterator = this.craftingLinks.values().iterator(); - while (craftingLinkIterator.hasNext()) - { - if ( craftingLinkIterator.next().isDead( this.grid, this ) ) - { - craftingLinkIterator.remove(); - } - } - - for (CraftingCPUCluster cpu : this.craftingCPUClusters) - { - cpu.updateCraftingLogic( this.grid, this.energyGrid, this ); - } - } - - @MENetworkEventSubscribe - public void updateCPUClusters(MENetworkCraftingCpuChange c) - { - this.updateList = true; - } - - @MENetworkEventSubscribe - public void updateCPUClusters(MENetworkCraftingPatternChange c) - { - this.updatePatterns(); - } - - @Override - public void removeNode(IGridNode gridNode, IGridHost machine) - { - if ( machine instanceof ICraftingWatcherHost ) - { - ICraftingWatcher craftingWatcher = this.craftingWatchers.get( machine ); - if ( craftingWatcher != null ) - { - craftingWatcher.clear(); - this.craftingWatchers.remove( machine ); - } - } - - if ( machine instanceof ICraftingRequester ) - { - for (CraftingLinkNexus link : this.craftingLinks.values()) - { - if ( link.isMachine( machine ) ) - { - link.removeNode(); - } - } - } - - if ( machine instanceof TileCraftingTile ) - { - this.updateList = true; - } - - if ( machine instanceof ICraftingProvider ) - { - this.craftingProviders.remove( machine ); - this.updatePatterns(); - } - } - - @Override - public void addNode(IGridNode gridNode, IGridHost machine) - { - if ( machine instanceof ICraftingWatcherHost ) - { - ICraftingWatcherHost watcherHost = (ICraftingWatcherHost) machine; - CraftingWatcher watcher = new CraftingWatcher( this, watcherHost ); - this.craftingWatchers.put( gridNode, watcher ); - watcherHost.updateWatcher( watcher ); - } - - if ( machine instanceof ICraftingRequester ) - { - for (ICraftingLink link : ((ICraftingRequester) machine).getRequestedJobs()) - { - if ( link instanceof CraftingLink ) - { - this.addLink( (CraftingLink) link ); - } - } - } - - if ( machine instanceof TileCraftingTile ) - { - this.updateList = true; - } - - if ( machine instanceof ICraftingProvider ) - { - this.craftingProviders.add( (ICraftingProvider) machine ); - this.updatePatterns(); - } - } - - private void updateCPUClusters() - { - this.craftingCPUClusters.clear(); - - for (IGridNode cst : this.grid.getMachines( TileCraftingStorageTile.class )) - { - TileCraftingStorageTile tile = (TileCraftingStorageTile) cst.getMachine(); - CraftingCPUCluster cluster = (CraftingCPUCluster) tile.getCluster(); - if ( cluster != null ) - { - this.craftingCPUClusters.add( cluster ); - - if ( cluster.myLastLink != null ) - { - this.addLink( (CraftingLink) cluster.myLastLink ); - } - } - } - } - - @Override - public void addCraftingOption(ICraftingMedium medium, ICraftingPatternDetails api) - { - List details = this.craftingMethods.get( api ); - if ( details == null ) - { - details = new ArrayList(); - details.add( medium ); - this.craftingMethods.put( api, details ); - } - else - { - details.add( medium ); - } - } - - static final Comparator COMPARATOR = new Comparator() - { - @Override - public int compare(ICraftingPatternDetails firstDetail, ICraftingPatternDetails nextDetail) - { - return nextDetail.getPriority() - firstDetail.getPriority(); - } - }; - - private void updatePatterns() - { - Map> oldItems = this.craftableItems; - - // erase list. - this.craftingMethods.clear(); - this.craftableItems.clear(); - this.emitableItems.clear(); - - // update the stuff that was in the list... - this.storageGrid.postAlterationOfStoredItems( StorageChannel.ITEMS, oldItems.keySet(), new BaseActionSource() ); - - // re-create list.. - for (ICraftingProvider provider : this.craftingProviders) - { - provider.provideCrafting( this ); - } - - Map> tmpCraft = new HashMap>(); - - // new craftables! - for (ICraftingPatternDetails details : this.craftingMethods.keySet()) - { - for (IAEItemStack out : details.getOutputs()) - { - out = out.copy(); - out.reset(); - out.setCraftable( true ); - - Set methods = tmpCraft.get( out ); - - if ( methods == null ) - { - tmpCraft.put( out, methods = new TreeSet( COMPARATOR ) ); - } - - methods.add( details ); - } - } - - // make them immutable - for (Entry> e : tmpCraft.entrySet()) - { - this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) ); - } - - this.storageGrid.postAlterationOfStoredItems( StorageChannel.ITEMS, this.craftableItems.keySet(), new BaseActionSource() ); - } - - @Override - public void onSplit(IGridStorage destinationStorage) - { // nothing! - } - - @Override - public void onJoin(IGridStorage sourceStorage) - { - // nothing! - } - - @Override - public void populateGridStorage(IGridStorage destinationStorage) - { - // nothing! - } - - @Override - public List getCellArray(StorageChannel channel) - { - List list = new ArrayList( 1 ); - - if ( channel == StorageChannel.ITEMS ) - { - list.add( this ); - } - - return list; - } - - @Override - public int getPriority() - { - return Integer.MAX_VALUE; - } - - @Override - public IAEStack extractItems(IAEStack request, Actionable mode, BaseActionSource src) - { - return null; - } - - @Override - public IItemList getAvailableItems(IItemList out) - { - // add craftable items! - for (IAEItemStack stack : this.craftableItems.keySet()) - { - out.addCrafting( stack ); - } - - for (IAEItemStack st : this.emitableItems) - { - out.addCrafting( st ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.WRITE; - } - - @Override - public boolean isPrioritized(IAEStack input) - { - return true; - } - - @Override - public IAEStack injectItems(IAEStack input, Actionable type, BaseActionSource src) - { - for (CraftingCPUCluster cpu : this.craftingCPUClusters) - { - input = cpu.injectItems( input, type, src ); - } - - return input; - } - - @Override - public boolean canAccept(IAEStack input) - { - for (CraftingCPUCluster cpu : this.craftingCPUClusters) - { - if ( cpu.canAccept( input ) ) - { - return true; - } - } - - return false; - } - - @Override - public ICraftingLink submitJob(ICraftingJob job, ICraftingRequester requestingMachine, ICraftingCPU target, final boolean prioritizePower, BaseActionSource src) - { - if ( job.isSimulation() ) - { - return null; - } - - CraftingCPUCluster cpuCluster = null; - - if ( target instanceof CraftingCPUCluster ) - { - cpuCluster = (CraftingCPUCluster) target; - } - - if ( target == null ) - { - List validCpusClusters = new ArrayList(); - for (CraftingCPUCluster cpu : this.craftingCPUClusters) - { - if ( cpu.isActive() && !cpu.isBusy() && cpu.getAvailableStorage() >= job.getByteTotal() ) - { - validCpusClusters.add( cpu ); - } - } - - Collections.sort( validCpusClusters, new Comparator() - { - @Override - public int compare(CraftingCPUCluster firstCluster, CraftingCPUCluster nextCluster) - { - if ( prioritizePower ) - { - int comparison = ItemSorters.compareLong( nextCluster.getCoProcessors(), firstCluster.getCoProcessors() ); - if ( comparison != 0 ) - return comparison; - return ItemSorters.compareLong( nextCluster.getAvailableStorage(), firstCluster.getAvailableStorage() ); - } - - int comparison = ItemSorters.compareLong( firstCluster.getCoProcessors(), nextCluster.getCoProcessors() ); - if ( comparison != 0 ) - return comparison; - return ItemSorters.compareLong( firstCluster.getAvailableStorage(), nextCluster.getAvailableStorage() ); - } - - } ); - - if ( !validCpusClusters.isEmpty() ) - { - cpuCluster = validCpusClusters.get( 0 ); - } - } - - if ( cpuCluster != null ) - { - return cpuCluster.submitJob( this.grid, job, src, requestingMachine ); - } - - return null; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public ImmutableCollection getCraftingFor(IAEItemStack whatToCraft, ICraftingPatternDetails details, int slotIndex, World world) - { - ImmutableList res = this.craftableItems.get( whatToCraft ); - - if ( res == null ) - { - if ( details != null && details.isCraftable() ) - { - for (IAEItemStack ais : this.craftableItems.keySet()) - { - if ( ais.getItem() == whatToCraft.getItem() && (!ais.getItem().getHasSubtypes() || ais.getItemDamage() == whatToCraft.getItemDamage()) ) - { - if ( details.isValidItemForSlot( slotIndex, ais.getItemStack(), world ) ) - { - return this.craftableItems.get( ais ); - } - } - } - } - - return ImmutableSet.of(); - } - - return res; - } - - public List getMediums(ICraftingPatternDetails key) - { - List mediums = this.craftingMethods.get( key ); - - if ( mediums == null ) - { - mediums = ImmutableList.of(); - } - - return mediums; - } - - @Override - public boolean validForPass(int i) - { - return i == 1; - } - - final public static ExecutorService CRAFTING_POOL; - - static - { - ThreadFactory factory = new ThreadFactory() { - - @Override - public Thread newThread(Runnable ar) - { - return new Thread( ar, "AE Crafting Calculator" ); - } - - }; - - CRAFTING_POOL = Executors.newCachedThreadPool( factory ); - } - - @Override - public Future beginCraftingJob(World world, IGrid grid, BaseActionSource actionSrc, IAEItemStack slotItem, ICraftingCallback cb) - { - if ( world == null || grid == null || actionSrc == null || slotItem == null ) - { - throw new RuntimeException( "Invalid Crafting Job Request" ); - } - - CraftingJob job = new CraftingJob( world, grid, actionSrc, slotItem, cb ); - - return CRAFTING_POOL.submit( job, (ICraftingJob) job ); - } - - public boolean hasCpu(ICraftingCPU cpu) - { - return this.craftingCPUClusters.contains( cpu ); - } - - @Override - public boolean isRequesting(IAEItemStack what) - { - for (CraftingCPUCluster cluster : this.craftingCPUClusters) - { - if ( cluster.isMaking( what ) ) - { - return true; - } - } - - return false; - } - - @Override - public boolean canEmitFor(IAEItemStack someItem) - { - return this.emitableItems.contains( someItem ); - } - - @Override - public void setEmitable(IAEItemStack someItem) - { - this.emitableItems.add( someItem.copy() ); - } - } diff --git a/src/main/java/appeng/me/cache/EnergyGridCache.java b/src/main/java/appeng/me/cache/EnergyGridCache.java index db6433252..f964d3460 100644 --- a/src/main/java/appeng/me/cache/EnergyGridCache.java +++ b/src/main/java/appeng/me/cache/EnergyGridCache.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -53,96 +54,60 @@ import appeng.me.GridNode; import appeng.me.energy.EnergyThreshold; import appeng.me.energy.EnergyWatcher; + public class EnergyGridCache implements IEnergyGrid { + final public TreeSet interests = new TreeSet(); + final double AvgLength = 40.0; + final Set providers = new LinkedHashSet(); + final Set requesters = new LinkedHashSet(); + final Multiset energyGridProviders = HashMultiset.create(); + final IGrid myGrid; + final private HashMap watchers = new HashMap(); + final private Set localSeen = new HashSet(); /** * estimated power available. */ int availableTicksSinceUpdate = 0; double globalAvailablePower = 0; double globalMaxPower = 0; - /** * idle draw. */ double drainPerTick = 0; - - final double AvgLength = 40.0; - double avgDrainPerTick = 0; double avgInjectionPerTick = 0; - double tickDrainPerTick = 0; double tickInjectionPerTick = 0; - /** * power status */ boolean publicHasPower = false; boolean hasPower = true; long ticksSinceHasPowerChange = 900; - /** * excess power in the system. */ double extra = 0; - IAEPowerStorage lastProvider; - final Set providers = new LinkedHashSet(); - IAEPowerStorage lastRequester; - final Set requesters = new LinkedHashSet(); - - final public TreeSet interests = new TreeSet(); - final private HashMap watchers = new HashMap(); - - final private Set localSeen = new HashSet(); - - private double buffer() - { - return this.providers.isEmpty() ? 1000.0 : 0.0; - } - - private IAEPowerStorage getFirstRequester() - { - if ( this.lastRequester == null ) - { - Iterator i = this.requesters.iterator(); - this.lastRequester = i.hasNext() ? i.next() : null; - } - - return this.lastRequester; - } - - private IAEPowerStorage getFirstProvider() - { - if ( this.lastProvider == null ) - { - Iterator i = this.providers.iterator(); - this.lastProvider = i.hasNext() ? i.next() : null; - } - - return this.lastProvider; - } - - final Multiset energyGridProviders = HashMultiset.create(); - - final IGrid myGrid; PathGridCache pgc; + double lastStoredPower = -1; - public EnergyGridCache(IGrid g) { + public EnergyGridCache( IGrid g ) + { this.myGrid = g; } @MENetworkEventSubscribe - public void postInit(MENetworkPostCacheConstruction pcc) + public void postInit( MENetworkPostCacheConstruction pcc ) { this.pgc = this.myGrid.getCache( IPathingGrid.class ); } @MENetworkEventSubscribe - public void EnergyNodeChanges(MENetworkPowerIdleChange ev) + public void EnergyNodeChanges( MENetworkPowerIdleChange ev ) { // update power usage based on event. GridNode node = (GridNode) ev.node; @@ -156,88 +121,188 @@ public class EnergyGridCache implements IEnergyGrid } @MENetworkEventSubscribe - public void EnergyNodeChanges(MENetworkPowerStorage ev) + public void EnergyNodeChanges( MENetworkPowerStorage ev ) { - if ( ev.storage.isAEPublicPowerStorage() ) + if( ev.storage.isAEPublicPowerStorage() ) { - switch (ev.type) + switch( ev.type ) { - case PROVIDE_POWER: - if ( ev.storage.getPowerFlow() != AccessRestriction.WRITE ) - this.providers.add( ev.storage ); - break; - case REQUEST_POWER: - if ( ev.storage.getPowerFlow() != AccessRestriction.READ ) - this.requesters.add( ev.storage ); - break; + case PROVIDE_POWER: + if( ev.storage.getPowerFlow() != AccessRestriction.WRITE ) + this.providers.add( ev.storage ); + break; + case REQUEST_POWER: + if( ev.storage.getPowerFlow() != AccessRestriction.READ ) + this.requesters.add( ev.storage ); + break; } } else { - (new RuntimeException( "Attempt to ask the IEnergyGrid to charge a non public energy store." )).printStackTrace(); + ( new RuntimeException( "Attempt to ask the IEnergyGrid to charge a non public energy store." ) ).printStackTrace(); } } @Override - public double getEnergyDemand(double maxRequired) + public void onUpdateTick() { - this.localSeen.clear(); - return this.getEnergyDemand( maxRequired, this.localSeen ); + if( !this.interests.isEmpty() ) + { + double oldPower = this.lastStoredPower; + this.lastStoredPower = this.getStoredPower(); + + EnergyThreshold low = new EnergyThreshold( Math.min( oldPower, this.lastStoredPower ), null ); + EnergyThreshold high = new EnergyThreshold( Math.max( oldPower, this.lastStoredPower ), null ); + for( EnergyThreshold th : this.interests.subSet( low, true, high, true ) ) + { + ( (EnergyWatcher) th.watcher ).post( this ); + } + } + + this.avgDrainPerTick *= ( this.AvgLength - 1 ) / this.AvgLength; + this.avgInjectionPerTick *= ( this.AvgLength - 1 ) / this.AvgLength; + + this.avgDrainPerTick += this.tickDrainPerTick / this.AvgLength; + this.avgInjectionPerTick += this.tickInjectionPerTick / this.AvgLength; + + this.tickDrainPerTick = 0; + this.tickInjectionPerTick = 0; + + // power information. + boolean currentlyHasPower = false; + + if( this.drainPerTick > 0.0001 ) + { + double drained = this.extractAEPower( this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG ); + currentlyHasPower = drained >= this.drainPerTick - 0.001; + } + else + { + currentlyHasPower = this.extractAEPower( 0.1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0; + } + + // ticks since change.. + if( currentlyHasPower == this.hasPower ) + this.ticksSinceHasPowerChange++; + else + this.ticksSinceHasPowerChange = 0; + + // update status.. + this.hasPower = currentlyHasPower; + + // update public status, this buffers power ups for 30 ticks. + if( this.hasPower && this.ticksSinceHasPowerChange > 30 ) + this.publicPowerState( true, this.myGrid ); + else if( !this.hasPower ) + this.publicPowerState( false, this.myGrid ); + + this.availableTicksSinceUpdate++; } @Override - public double getEnergyDemand(double maxRequired, Set seen) + public double extractAEPower( double amt, Actionable mode, PowerMultiplier pm ) { - if ( !seen.add( this ) ) + this.localSeen.clear(); + return pm.divide( this.extractAEPower( pm.multiply( amt ), mode, this.localSeen ) ); + } + + @Override + public double getIdlePowerUsage() + { + return this.drainPerTick + this.pgc.channelPowerUsage; + } + + private void publicPowerState( boolean newState, IGrid grid ) + { + if( this.publicHasPower == newState ) + return; + + this.publicHasPower = newState; + ( (Grid) this.myGrid ).setImportantFlag( 0, this.publicHasPower ); + grid.postEvent( new MENetworkPowerStatusChange() ); + } + + /** + * refresh current stored power. + */ + public void refreshPower() + { + this.availableTicksSinceUpdate = 0; + this.globalAvailablePower = 0; + for( IAEPowerStorage p : this.providers ) + this.globalAvailablePower += p.getAECurrentPower(); + } + + @Override + public double extractAEPower( double amt, Actionable mode, Set seen ) + { + if( !seen.add( this ) ) return 0; - double required = this.buffer() - this.extra; + double extractedPower = this.extra; - Iterator it = this.requesters.iterator(); - while (required < maxRequired && it.hasNext()) + if( mode == Actionable.SIMULATE ) { - IAEPowerStorage node = it.next(); - if ( node.getPowerFlow() != AccessRestriction.READ ) - required += Math.max( 0.0, node.getAEMaxPower() - node.getAECurrentPower() ); + extractedPower += this.simulateExtract( extractedPower, amt ); + + if( extractedPower < amt ) + { + Iterator i = this.energyGridProviders.iterator(); + while( extractedPower < amt && i.hasNext() ) + extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen ); + } + + return extractedPower; + } + else + { + this.extra = 0; + extractedPower = this.doExtract( extractedPower, amt ); } - Iterator ix = this.energyGridProviders.iterator(); - while (required < maxRequired && ix.hasNext()) + // got more then we wanted? + if( extractedPower > amt ) { - IEnergyGridProvider node = ix.next(); - required += node.getEnergyDemand( maxRequired - required, seen ); + this.extra = extractedPower - amt; + this.globalAvailablePower -= amt; + + this.tickDrainPerTick += amt; + return amt; } - return required; + if( extractedPower < amt ) + { + Iterator i = this.energyGridProviders.iterator(); + while( extractedPower < amt && i.hasNext() ) + extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen ); + } + + // go less or the correct amount? + this.globalAvailablePower -= extractedPower; + this.tickDrainPerTick += extractedPower; + return extractedPower; } @Override - public double injectPower(double amt, Actionable mode) + public double injectAEPower( double amt, Actionable mode, Set seen ) { - this.localSeen.clear(); - return this.injectAEPower( amt, mode, this.localSeen ); - } - - @Override - public double injectAEPower(double amt, Actionable mode, Set seen) - { - if ( !seen.add( this ) ) + if( !seen.add( this ) ) return 0; double ignore = this.extra; amt += this.extra; - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) { Iterator it = this.requesters.iterator(); - while (amt > 0 && it.hasNext()) + while( amt > 0 && it.hasNext() ) { IAEPowerStorage node = it.next(); amt = node.injectAEPower( amt, Actionable.SIMULATE ); } Iterator i = this.energyGridProviders.iterator(); - while (amt > 0 && i.hasNext()) + while( amt > 0 && i.hasNext() ) amt = i.next().injectAEPower( amt, mode, seen ); } else @@ -245,12 +310,12 @@ public class EnergyGridCache implements IEnergyGrid this.tickInjectionPerTick += amt - ignore; // totalInjectionPastTicks[0] += i; - while (amt > 0 && !this.requesters.isEmpty()) + while( amt > 0 && !this.requesters.isEmpty() ) { IAEPowerStorage node = this.getFirstRequester(); amt = node.injectAEPower( amt, Actionable.MODULATE ); - if ( amt > 0 ) + if( amt > 0 ) { this.requesters.remove( node ); this.lastRequester = null; @@ -258,7 +323,7 @@ public class EnergyGridCache implements IEnergyGrid } Iterator i = this.energyGridProviders.iterator(); - while (amt > 0 && i.hasNext()) + while( amt > 0 && i.hasNext() ) { IEnergyGridProvider what = i.next(); Set listCopy = new HashSet(); @@ -277,275 +342,36 @@ public class EnergyGridCache implements IEnergyGrid } @Override - public double extractAEPower(double amt, Actionable mode, PowerMultiplier pm) + public double getEnergyDemand( double maxRequired, Set seen ) { - this.localSeen.clear(); - return pm.divide( this.extractAEPower( pm.multiply( amt ), mode, this.localSeen ) ); - } - - @Override - public void addNode(IGridNode node, IGridHost machine) - { - if ( machine instanceof IEnergyGridProvider ) - this.energyGridProviders.add( (IEnergyGridProvider) machine ); - - // idle draw... - GridNode gridNode = (GridNode) node; - IGridBlock gb = gridNode.getGridBlock(); - gridNode.previousDraw = gb.getIdlePowerUsage(); - this.drainPerTick += gridNode.previousDraw; - - // power storage - if ( machine instanceof IAEPowerStorage ) - { - IAEPowerStorage ps = (IAEPowerStorage) machine; - if ( ps.isAEPublicPowerStorage() ) - { - double max = ps.getAEMaxPower(); - double current = ps.getAECurrentPower(); - - if ( ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalMaxPower += ps.getAEMaxPower(); - } - - if ( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalAvailablePower += current; - this.providers.add( ps ); - } - - if ( current < max && ps.getPowerFlow() != AccessRestriction.READ ) - this.requesters.add( ps ); - } - } - - if ( machine instanceof IEnergyWatcherHost ) - { - IEnergyWatcherHost swh = (IEnergyWatcherHost) machine; - EnergyWatcher iw = new EnergyWatcher( this, swh ); - this.watchers.put( node, iw ); - swh.updateWatcher( iw ); - } - - this.myGrid.postEventTo( node, new MENetworkPowerStatusChange() ); - } - - @Override - public void removeNode(IGridNode node, IGridHost machine) - { - if ( machine instanceof IEnergyGridProvider ) - this.energyGridProviders.remove( machine ); - - // idle draw. - GridNode gridNode = (GridNode) node; - this.drainPerTick -= gridNode.previousDraw; - - // power storage. - if ( machine instanceof IAEPowerStorage ) - { - IAEPowerStorage ps = (IAEPowerStorage) machine; - if ( ps.isAEPublicPowerStorage() ) - { - if ( ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalMaxPower -= ps.getAEMaxPower(); - this.globalAvailablePower -= ps.getAECurrentPower(); - } - - if ( this.lastProvider == machine ) - this.lastProvider = null; - - if ( this.lastRequester == machine ) - this.lastRequester = null; - - this.providers.remove( machine ); - this.requesters.remove( machine ); - } - } - - if ( machine instanceof IStackWatcherHost ) - { - IEnergyWatcher myWatcher = this.watchers.get( machine ); - if ( myWatcher != null ) - { - myWatcher.clear(); - this.watchers.remove( machine ); - } - } - - } - - double lastStoredPower = -1; - - @Override - public void onUpdateTick() - { - if ( !this.interests.isEmpty() ) - { - double oldPower = this.lastStoredPower; - this.lastStoredPower = this.getStoredPower(); - - EnergyThreshold low = new EnergyThreshold( Math.min( oldPower, this.lastStoredPower ), null ); - EnergyThreshold high = new EnergyThreshold( Math.max( oldPower, this.lastStoredPower ), null ); - for (EnergyThreshold th : this.interests.subSet( low, true, high, true )) - { - ((EnergyWatcher) th.watcher).post( this ); - } - } - - this.avgDrainPerTick *= (this.AvgLength - 1) / this.AvgLength; - this.avgInjectionPerTick *= (this.AvgLength - 1) / this.AvgLength; - - this.avgDrainPerTick += this.tickDrainPerTick / this.AvgLength; - this.avgInjectionPerTick += this.tickInjectionPerTick / this.AvgLength; - - this.tickDrainPerTick = 0; - this.tickInjectionPerTick = 0; - - // power information. - boolean currentlyHasPower = false; - - if ( this.drainPerTick > 0.0001 ) - { - double drained = this.extractAEPower( this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG ); - currentlyHasPower = drained >= this.drainPerTick - 0.001; - } - else - { - currentlyHasPower = this.extractAEPower( 0.1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0; - } - - // ticks since change.. - if ( currentlyHasPower == this.hasPower ) - this.ticksSinceHasPowerChange++; - else - this.ticksSinceHasPowerChange = 0; - - // update status.. - this.hasPower = currentlyHasPower; - - // update public status, this buffers power ups for 30 ticks. - if ( this.hasPower && this.ticksSinceHasPowerChange > 30 ) - this.publicPowerState( true, this.myGrid ); - else if ( !this.hasPower ) - this.publicPowerState( false, this.myGrid ); - - this.availableTicksSinceUpdate++; - } - - private void publicPowerState(boolean newState, IGrid grid) - { - if ( this.publicHasPower == newState ) - return; - - this.publicHasPower = newState; - ((Grid) this.myGrid).setImportantFlag( 0, this.publicHasPower ); - grid.postEvent( new MENetworkPowerStatusChange() ); - } - - /** - * refresh current stored power. - */ - public void refreshPower() - { - this.availableTicksSinceUpdate = 0; - this.globalAvailablePower = 0; - for (IAEPowerStorage p : this.providers) - this.globalAvailablePower += p.getAECurrentPower(); - } - - @Override - public double getStoredPower() - { - if ( this.availableTicksSinceUpdate > 90 ) - this.refreshPower(); - - return Math.max( 0.0, this.globalAvailablePower ); - } - - @Override - public double getMaxStoredPower() - { - return this.globalMaxPower; - } - - @Override - public double extractAEPower(double amt, Actionable mode, Set seen) - { - if ( !seen.add( this ) ) + if( !seen.add( this ) ) return 0; - double extractedPower = this.extra; + double required = this.buffer() - this.extra; - if ( mode == Actionable.SIMULATE ) + Iterator it = this.requesters.iterator(); + while( required < maxRequired && it.hasNext() ) { - extractedPower += this.simulateExtract( extractedPower, amt ); - - if ( extractedPower < amt ) - { - Iterator i = this.energyGridProviders.iterator(); - while (extractedPower < amt && i.hasNext()) - extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen ); - } - - return extractedPower; - } - else - { - this.extra = 0; - extractedPower = this.doExtract( extractedPower, amt ); + IAEPowerStorage node = it.next(); + if( node.getPowerFlow() != AccessRestriction.READ ) + required += Math.max( 0.0, node.getAEMaxPower() - node.getAECurrentPower() ); } - // got more then we wanted? - if ( extractedPower > amt ) + Iterator ix = this.energyGridProviders.iterator(); + while( required < maxRequired && ix.hasNext() ) { - this.extra = extractedPower - amt; - this.globalAvailablePower -= amt; - - this.tickDrainPerTick += amt; - return amt; + IEnergyGridProvider node = ix.next(); + required += node.getEnergyDemand( maxRequired - required, seen ); } - if ( extractedPower < amt ) - { - Iterator i = this.energyGridProviders.iterator(); - while (extractedPower < amt && i.hasNext()) - extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen ); - } - - // go less or the correct amount? - this.globalAvailablePower -= extractedPower; - this.tickDrainPerTick += extractedPower; - return extractedPower; + return required; } - private double doExtract(double extractedPower, double amt) - { - while (extractedPower < amt && !this.providers.isEmpty()) - { - IAEPowerStorage node = this.getFirstProvider(); - - double req = amt - extractedPower; - double newPower = node.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.ONE ); - extractedPower += newPower; - - if ( newPower < req ) - { - this.providers.remove( node ); - this.lastProvider = null; - } - } - - // totalDrainPastTicks[0] += extractedPower; - return extractedPower; - } - - private double simulateExtract(double extractedPower, double amt) + private double simulateExtract( double extractedPower, double amt ) { Iterator it = this.providers.iterator(); - while (extractedPower < amt && it.hasNext()) + while( extractedPower < amt && it.hasNext() ) { IAEPowerStorage node = it.next(); @@ -557,16 +383,36 @@ public class EnergyGridCache implements IEnergyGrid return extractedPower; } - @Override - public boolean isNetworkPowered() + private double doExtract( double extractedPower, double amt ) { - return this.publicHasPower; + while( extractedPower < amt && !this.providers.isEmpty() ) + { + IAEPowerStorage node = this.getFirstProvider(); + + double req = amt - extractedPower; + double newPower = node.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.ONE ); + extractedPower += newPower; + + if( newPower < req ) + { + this.providers.remove( node ); + this.lastProvider = null; + } + } + + // totalDrainPastTicks[0] += extractedPower; + return extractedPower; } - @Override - public double getIdlePowerUsage() + private IAEPowerStorage getFirstProvider() { - return this.drainPerTick + this.pgc.channelPowerUsage; + if( this.lastProvider == null ) + { + Iterator i = this.providers.iterator(); + this.lastProvider = i.hasNext() ? i.next() : null; + } + + return this.lastProvider; } @Override @@ -582,22 +428,164 @@ public class EnergyGridCache implements IEnergyGrid } @Override - public void onSplit(IGridStorage storageB) + public boolean isNetworkPowered() + { + return this.publicHasPower; + } + + @Override + public double injectPower( double amt, Actionable mode ) + { + this.localSeen.clear(); + return this.injectAEPower( amt, mode, this.localSeen ); + } + + private IAEPowerStorage getFirstRequester() + { + if( this.lastRequester == null ) + { + Iterator i = this.requesters.iterator(); + this.lastRequester = i.hasNext() ? i.next() : null; + } + + return this.lastRequester; + } + + private double buffer() + { + return this.providers.isEmpty() ? 1000.0 : 0.0; + } + + @Override + public double getStoredPower() + { + if( this.availableTicksSinceUpdate > 90 ) + this.refreshPower(); + + return Math.max( 0.0, this.globalAvailablePower ); + } + + @Override + public double getMaxStoredPower() + { + return this.globalMaxPower; + } + + @Override + public double getEnergyDemand( double maxRequired ) + { + this.localSeen.clear(); + return this.getEnergyDemand( maxRequired, this.localSeen ); + } + + @Override + public void removeNode( IGridNode node, IGridHost machine ) + { + if( machine instanceof IEnergyGridProvider ) + this.energyGridProviders.remove( machine ); + + // idle draw. + GridNode gridNode = (GridNode) node; + this.drainPerTick -= gridNode.previousDraw; + + // power storage. + if( machine instanceof IAEPowerStorage ) + { + IAEPowerStorage ps = (IAEPowerStorage) machine; + if( ps.isAEPublicPowerStorage() ) + { + if( ps.getPowerFlow() != AccessRestriction.WRITE ) + { + this.globalMaxPower -= ps.getAEMaxPower(); + this.globalAvailablePower -= ps.getAECurrentPower(); + } + + if( this.lastProvider == machine ) + this.lastProvider = null; + + if( this.lastRequester == machine ) + this.lastRequester = null; + + this.providers.remove( machine ); + this.requesters.remove( machine ); + } + } + + if( machine instanceof IStackWatcherHost ) + { + IEnergyWatcher myWatcher = this.watchers.get( machine ); + if( myWatcher != null ) + { + myWatcher.clear(); + this.watchers.remove( machine ); + } + } + } + + @Override + public void addNode( IGridNode node, IGridHost machine ) + { + if( machine instanceof IEnergyGridProvider ) + this.energyGridProviders.add( (IEnergyGridProvider) machine ); + + // idle draw... + GridNode gridNode = (GridNode) node; + IGridBlock gb = gridNode.getGridBlock(); + gridNode.previousDraw = gb.getIdlePowerUsage(); + this.drainPerTick += gridNode.previousDraw; + + // power storage + if( machine instanceof IAEPowerStorage ) + { + IAEPowerStorage ps = (IAEPowerStorage) machine; + if( ps.isAEPublicPowerStorage() ) + { + double max = ps.getAEMaxPower(); + double current = ps.getAECurrentPower(); + + if( ps.getPowerFlow() != AccessRestriction.WRITE ) + { + this.globalMaxPower += ps.getAEMaxPower(); + } + + if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE ) + { + this.globalAvailablePower += current; + this.providers.add( ps ); + } + + if( current < max && ps.getPowerFlow() != AccessRestriction.READ ) + this.requesters.add( ps ); + } + } + + if( machine instanceof IEnergyWatcherHost ) + { + IEnergyWatcherHost swh = (IEnergyWatcherHost) machine; + EnergyWatcher iw = new EnergyWatcher( this, swh ); + this.watchers.put( node, iw ); + swh.updateWatcher( iw ); + } + + this.myGrid.postEventTo( node, new MENetworkPowerStatusChange() ); + } + + @Override + public void onSplit( IGridStorage storageB ) { this.extra /= 2; storageB.dataObject().setDouble( "extraEnergy", this.extra ); } @Override - public void onJoin(IGridStorage storageB) + public void onJoin( IGridStorage storageB ) { this.extra += storageB.dataObject().getDouble( "extraEnergy" ); } @Override - public void populateGridStorage(IGridStorage storage) + public void populateGridStorage( IGridStorage storage ) { storage.dataObject().setDouble( "extraEnergy", this.extra ); } - } diff --git a/src/main/java/appeng/me/cache/GridStorageCache.java b/src/main/java/appeng/me/cache/GridStorageCache.java index 75431f3a0..8b0ebd337 100644 --- a/src/main/java/appeng/me/cache/GridStorageCache.java +++ b/src/main/java/appeng/me/cache/GridStorageCache.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; @@ -53,25 +54,23 @@ import appeng.me.helpers.GenericInterestManager; import appeng.me.storage.ItemWatcher; import appeng.me.storage.NetworkInventoryHandler; + public class GridStorageCache implements IStorageGrid { - final private SetMultimap interests = HashMultimap.create(); - final public GenericInterestManager interestManager = new GenericInterestManager( this.interests ); - + final public IGrid myGrid; final HashSet activeCellProviders = new HashSet(); final HashSet inactiveCellProviders = new HashSet(); - final public IGrid myGrid; - - private NetworkInventoryHandler myItemNetwork; + final private SetMultimap interests = HashMultimap.create(); + final public GenericInterestManager interestManager = new GenericInterestManager( this.interests ); private final NetworkMonitor itemMonitor = new NetworkMonitor( this, StorageChannel.ITEMS ); - - private NetworkInventoryHandler myFluidNetwork; private final NetworkMonitor fluidMonitor = new NetworkMonitor( this, StorageChannel.FLUIDS ); - private final HashMap watchers = new HashMap(); + private NetworkInventoryHandler myItemNetwork; + private NetworkInventoryHandler myFluidNetwork; - public GridStorageCache(IGrid g) { + public GridStorageCache( IGrid g ) + { this.myGrid = g; } @@ -82,82 +81,86 @@ public class GridStorageCache implements IStorageGrid this.fluidMonitor.onTick(); } - private class CellChangeTrackerRecord + @Override + public void removeNode( IGridNode node, IGridHost machine ) { + if( machine instanceof ICellContainer ) + { + ICellContainer cc = (ICellContainer) machine; - final StorageChannel channel; - final int up_or_down; - final IItemList list; - final BaseActionSource src; - - public CellChangeTrackerRecord(StorageChannel channel, int i, IMEInventoryHandler h, BaseActionSource actionSrc) { - this.channel = channel; - this.up_or_down = i; - this.src = actionSrc; - - if ( channel == StorageChannel.ITEMS ) - this.list = ((IMEInventoryHandler) h).getAvailableItems( AEApi.instance().storage().createItemList() ); - else if ( channel == StorageChannel.FLUIDS ) - this.list = ((IMEInventoryHandler) h).getAvailableItems( AEApi.instance().storage().createFluidList() ); - else - this.list = null; + this.myGrid.postEvent( new MENetworkCellArrayUpdate() ); + this.removeCellProvider( cc, new CellChangeTracker() ).applyChanges(); + this.inactiveCellProviders.remove( cc ); } - public void applyChanges() + if( machine instanceof IStackWatcherHost ) { - GridStorageCache.this.postChangesToNetwork( this.channel, this.up_or_down, this.list, this.src ); - } - - } - - private class CellChangeTracker - { - - final List data = new LinkedList(); - - public void postChanges(StorageChannel channel, int i, IMEInventoryHandler h, BaseActionSource actionSrc) - { - this.data.add( new CellChangeTrackerRecord( channel, i, h, actionSrc ) ); - } - - public void applyChanges() - { - for (CellChangeTrackerRecord rec : this.data) - rec.applyChanges(); + IStackWatcher myWatcher = this.watchers.get( machine ); + if( myWatcher != null ) + { + myWatcher.clear(); + this.watchers.remove( machine ); + } } } @Override - public void registerCellProvider(ICellProvider provider) + public void addNode( IGridNode node, IGridHost machine ) { - this.inactiveCellProviders.add( provider ); - this.addCellProvider( provider, new CellChangeTracker() ).applyChanges(); + if( machine instanceof ICellContainer ) + { + ICellContainer cc = (ICellContainer) machine; + this.inactiveCellProviders.add( cc ); + + this.myGrid.postEvent( new MENetworkCellArrayUpdate() ); + if( node.isActive() ) + this.addCellProvider( cc, new CellChangeTracker() ).applyChanges(); + } + + if( machine instanceof IStackWatcherHost ) + { + IStackWatcherHost swh = (IStackWatcherHost) machine; + ItemWatcher iw = new ItemWatcher( this, swh ); + this.watchers.put( node, iw ); + swh.updateWatcher( iw ); + } } @Override - public void unregisterCellProvider(ICellProvider provider) + public void onSplit( IGridStorage storageB ) { - this.removeCellProvider( provider, new CellChangeTracker() ).applyChanges(); - this.inactiveCellProviders.remove( provider ); + } - public CellChangeTracker addCellProvider(ICellProvider cc, CellChangeTracker tracker) + @Override + public void onJoin( IGridStorage storageB ) { - if ( this.inactiveCellProviders.contains( cc ) ) + + } + + @Override + public void populateGridStorage( IGridStorage storage ) + { + + } + + public CellChangeTracker addCellProvider( ICellProvider cc, CellChangeTracker tracker ) + { + if( this.inactiveCellProviders.contains( cc ) ) { this.inactiveCellProviders.remove( cc ); this.activeCellProviders.add( cc ); BaseActionSource actionSrc = new BaseActionSource(); - if ( cc instanceof IActionHost ) + if( cc instanceof IActionHost ) actionSrc = new MachineSource( (IActionHost) cc ); - for (IMEInventoryHandler h : cc.getCellArray( StorageChannel.ITEMS )) + for( IMEInventoryHandler h : cc.getCellArray( StorageChannel.ITEMS ) ) { tracker.postChanges( StorageChannel.ITEMS, 1, h, actionSrc ); } - for (IMEInventoryHandler h : cc.getCellArray( StorageChannel.FLUIDS )) + for( IMEInventoryHandler h : cc.getCellArray( StorageChannel.FLUIDS ) ) { tracker.postChanges( StorageChannel.FLUIDS, 1, h, actionSrc ); } @@ -166,23 +169,23 @@ public class GridStorageCache implements IStorageGrid return tracker; } - public CellChangeTracker removeCellProvider(ICellProvider cc, CellChangeTracker tracker) + public CellChangeTracker removeCellProvider( ICellProvider cc, CellChangeTracker tracker ) { - if ( this.activeCellProviders.contains( cc ) ) + if( this.activeCellProviders.contains( cc ) ) { this.inactiveCellProviders.add( cc ); this.activeCellProviders.remove( cc ); BaseActionSource actionSrc = new BaseActionSource(); - if ( cc instanceof IActionHost ) + if( cc instanceof IActionHost ) actionSrc = new MachineSource( (IActionHost) cc ); - for (IMEInventoryHandler h : cc.getCellArray( StorageChannel.ITEMS )) + for( IMEInventoryHandler h : cc.getCellArray( StorageChannel.ITEMS ) ) { tracker.postChanges( StorageChannel.ITEMS, -1, h, actionSrc ); } - for (IMEInventoryHandler h : cc.getCellArray( StorageChannel.FLUIDS )) + for( IMEInventoryHandler h : cc.getCellArray( StorageChannel.FLUIDS ) ) { tracker.postChanges( StorageChannel.FLUIDS, -1, h, actionSrc ); } @@ -192,7 +195,7 @@ public class GridStorageCache implements IStorageGrid } @MENetworkEventSubscribe - public void cellUpdate(MENetworkCellArrayUpdate ev) + public void cellUpdate( MENetworkCellArrayUpdate ev ) { this.myItemNetwork = null; this.myFluidNetwork = null; @@ -203,20 +206,20 @@ public class GridStorageCache implements IStorageGrid CellChangeTracker tracker = new CellChangeTracker(); - for (ICellProvider cc : ll) + for( ICellProvider cc : ll ) { boolean Active = true; - if ( cc instanceof IActionHost ) + if( cc instanceof IActionHost ) { - IGridNode node = ((IActionHost) cc).getActionableNode(); - if ( node != null && node.isActive() ) + IGridNode node = ( (IActionHost) cc ).getActionableNode(); + if( node != null && node.isActive() ) Active = true; else Active = false; } - if ( Active ) + if( Active ) this.addCellProvider( cc, tracker ); else this.removeCellProvider( cc, tracker ); @@ -228,118 +231,81 @@ public class GridStorageCache implements IStorageGrid tracker.applyChanges(); } - @Override - public void removeNode(IGridNode node, IGridHost machine) + private void postChangesToNetwork( StorageChannel chan, int up_or_down, IItemList availableItems, BaseActionSource src ) { - if ( machine instanceof ICellContainer ) + switch( chan ) { - ICellContainer cc = (ICellContainer) machine; - - this.myGrid.postEvent( new MENetworkCellArrayUpdate() ); - this.removeCellProvider( cc, new CellChangeTracker() ).applyChanges(); - this.inactiveCellProviders.remove( cc ); - } - - if ( machine instanceof IStackWatcherHost ) - { - IStackWatcher myWatcher = this.watchers.get( machine ); - if ( myWatcher != null ) - { - myWatcher.clear(); - this.watchers.remove( machine ); - } - } - } - - @Override - public void addNode(IGridNode node, IGridHost machine) - { - if ( machine instanceof ICellContainer ) - { - ICellContainer cc = (ICellContainer) machine; - this.inactiveCellProviders.add( cc ); - - this.myGrid.postEvent( new MENetworkCellArrayUpdate() ); - if ( node.isActive() ) - this.addCellProvider( cc, new CellChangeTracker() ).applyChanges(); - } - - if ( machine instanceof IStackWatcherHost ) - { - IStackWatcherHost swh = (IStackWatcherHost) machine; - ItemWatcher iw = new ItemWatcher( this, swh ); - this.watchers.put( node, iw ); - swh.updateWatcher( iw ); - } - } - - private void buildNetworkStorage(StorageChannel chan) - { - SecurityCache security = this.myGrid.getCache( ISecurityGrid.class ); - - switch (chan) - { - case FLUIDS: - this.myFluidNetwork = new NetworkInventoryHandler( StorageChannel.FLUIDS, security ); - for (ICellProvider cc : this.activeCellProviders) - { - for (IMEInventoryHandler h : cc.getCellArray( chan )) - this.myFluidNetwork.addNewStorage( h ); - } - break; - case ITEMS: - this.myItemNetwork = new NetworkInventoryHandler( StorageChannel.ITEMS, security ); - for (ICellProvider cc : this.activeCellProviders) - { - for (IMEInventoryHandler h : cc.getCellArray( chan )) - this.myItemNetwork.addNewStorage( h ); - } - break; - default: - } - } - - private void postChangesToNetwork(StorageChannel chan, int up_or_down, IItemList availableItems, BaseActionSource src) - { - switch (chan) - { - case FLUIDS: - this.fluidMonitor.postChange( up_or_down > 0, availableItems, src ); - break; - case ITEMS: - this.itemMonitor.postChange( up_or_down > 0, availableItems, src ); - break; - default: + case FLUIDS: + this.fluidMonitor.postChange( up_or_down > 0, availableItems, src ); + break; + case ITEMS: + this.itemMonitor.postChange( up_or_down > 0, availableItems, src ); + break; + default: } } public IMEInventoryHandler getItemInventoryHandler() { - if ( this.myItemNetwork == null ) + if( this.myItemNetwork == null ) this.buildNetworkStorage( StorageChannel.ITEMS ); return this.myItemNetwork; } + private void buildNetworkStorage( StorageChannel chan ) + { + SecurityCache security = this.myGrid.getCache( ISecurityGrid.class ); + + switch( chan ) + { + case FLUIDS: + this.myFluidNetwork = new NetworkInventoryHandler( StorageChannel.FLUIDS, security ); + for( ICellProvider cc : this.activeCellProviders ) + { + for( IMEInventoryHandler h : cc.getCellArray( chan ) ) + this.myFluidNetwork.addNewStorage( h ); + } + break; + case ITEMS: + this.myItemNetwork = new NetworkInventoryHandler( StorageChannel.ITEMS, security ); + for( ICellProvider cc : this.activeCellProviders ) + { + for( IMEInventoryHandler h : cc.getCellArray( chan ) ) + this.myItemNetwork.addNewStorage( h ); + } + break; + default: + } + } + public IMEInventoryHandler getFluidInventoryHandler() { - if ( this.myFluidNetwork == null ) + if( this.myFluidNetwork == null ) this.buildNetworkStorage( StorageChannel.FLUIDS ); return this.myFluidNetwork; } @Override - public void postAlterationOfStoredItems(StorageChannel chan, Iterable input, BaseActionSource src) + public void postAlterationOfStoredItems( StorageChannel chan, Iterable input, BaseActionSource src ) { - if ( chan == StorageChannel.ITEMS ) + if( chan == StorageChannel.ITEMS ) this.itemMonitor.postChange( true, (Iterable) input, src ); - else if ( chan == StorageChannel.FLUIDS ) + else if( chan == StorageChannel.FLUIDS ) this.fluidMonitor.postChange( true, (Iterable) input, src ); } @Override - public IMEMonitor getFluidInventory() + public void registerCellProvider( ICellProvider provider ) { - return this.fluidMonitor; + this.inactiveCellProviders.add( provider ); + this.addCellProvider( provider, new CellChangeTracker() ).applyChanges(); + } + + @Override + public void unregisterCellProvider( ICellProvider provider ) + { + this.removeCellProvider( provider, new CellChangeTracker() ).applyChanges(); + this.inactiveCellProviders.remove( provider ); } @Override @@ -349,21 +315,54 @@ public class GridStorageCache implements IStorageGrid } @Override - public void onSplit(IGridStorage storageB) + public IMEMonitor getFluidInventory() { - + return this.fluidMonitor; } - @Override - public void onJoin(IGridStorage storageB) + private class CellChangeTrackerRecord { + final StorageChannel channel; + final int up_or_down; + final IItemList list; + final BaseActionSource src; + + public CellChangeTrackerRecord( StorageChannel channel, int i, IMEInventoryHandler h, BaseActionSource actionSrc ) + { + this.channel = channel; + this.up_or_down = i; + this.src = actionSrc; + + if( channel == StorageChannel.ITEMS ) + this.list = ( (IMEInventoryHandler) h ).getAvailableItems( AEApi.instance().storage().createItemList() ); + else if( channel == StorageChannel.FLUIDS ) + this.list = ( (IMEInventoryHandler) h ).getAvailableItems( AEApi.instance().storage().createFluidList() ); + else + this.list = null; + } + + public void applyChanges() + { + GridStorageCache.this.postChangesToNetwork( this.channel, this.up_or_down, this.list, this.src ); + } } - @Override - public void populateGridStorage(IGridStorage storage) + + private class CellChangeTracker { - } + final List data = new LinkedList(); + public void postChanges( StorageChannel channel, int i, IMEInventoryHandler h, BaseActionSource actionSrc ) + { + this.data.add( new CellChangeTrackerRecord( channel, i, h, actionSrc ) ); + } + + public void applyChanges() + { + for( CellChangeTrackerRecord rec : this.data ) + rec.applyChanges(); + } + } } diff --git a/src/main/java/appeng/me/cache/NetworkMonitor.java b/src/main/java/appeng/me/cache/NetworkMonitor.java index c3a868f64..09b4a8892 100644 --- a/src/main/java/appeng/me/cache/NetworkMonitor.java +++ b/src/main/java/appeng/me/cache/NetworkMonitor.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.Collection; import java.util.Deque; import java.util.Iterator; @@ -34,94 +35,42 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; import appeng.me.storage.ItemWatcher; + public class NetworkMonitor> extends MEMonitorHandler { + private final static Deque> DEPTH = new LinkedList>(); final private GridStorageCache myGridCache; final private StorageChannel myChannel; - boolean sendEvent = false; + public NetworkMonitor( GridStorageCache cache, StorageChannel chan ) + { + super( null, chan ); + this.myGridCache = cache; + this.myChannel = chan; + } + public void forceUpdate() { this.hasChanged = true; Iterator, Object>> i = this.getListeners(); - while (i.hasNext()) + while( i.hasNext() ) { Entry, Object> o = i.next(); IMEMonitorHandlerReceiver receiver = o.getKey(); - if ( receiver.isValid( o.getValue() ) ) + if( receiver.isValid( o.getValue() ) ) receiver.onListUpdate(); else i.remove(); } } - public NetworkMonitor(GridStorageCache cache, StorageChannel chan) { - super( null, chan ); - this.myGridCache = cache; - this.myChannel = chan; - } - - private final static Deque> DEPTH = new LinkedList>(); - - @Override - protected void postChangesToListeners(Iterable changes, BaseActionSource src) - { - this.postChange( true, changes, src ); - } - - protected void postChange(boolean Add, Iterable changes, BaseActionSource src) - { - if ( DEPTH.contains( this ) ) - return; - - DEPTH.push( this ); - - this.sendEvent = true; - this.notifyListenersOfChange( changes, src ); - - IItemList myStorageList = this.getStorageList(); - - for (T changedItem : changes) - { - T difference = changedItem; - - if ( !Add && changedItem != null ) - (difference = changedItem.copy()).setStackSize( -changedItem.getStackSize() ); - - if ( this.myGridCache.interestManager.containsKey( changedItem ) ) - { - Collection list = this.myGridCache.interestManager.get( changedItem ); - if ( !list.isEmpty() ) - { - IAEStack fullStack = myStorageList.findPrecise( changedItem ); - if ( fullStack == null ) - { - fullStack = changedItem.copy(); - fullStack.setStackSize( 0 ); - } - - this.myGridCache.interestManager.enableTransactions(); - - for (ItemWatcher iw : list) - iw.getHost().onStackChange( myStorageList, fullStack, difference, src, this.getChannel() ); - - this.myGridCache.interestManager.disableTransactions(); - } - } - } - - final NetworkMonitor last = DEPTH.pop(); - if ( last != this ) - throw new RuntimeException( "Invalid Access to Networked Storage API detected." ); - } - public void onTick() { - if ( this.sendEvent ) + if( this.sendEvent ) { this.sendEvent = false; this.myGridCache.myGrid.postEvent( new MENetworkStorageEvent( this, this.myChannel ) ); @@ -131,15 +80,66 @@ public class NetworkMonitor> extends MEMonitorHandler @Override protected IMEInventoryHandler getHandler() { - switch (this.myChannel) + switch( this.myChannel ) { - case ITEMS: - return this.myGridCache.getItemInventoryHandler(); - case FLUIDS: - return this.myGridCache.getFluidInventoryHandler(); - default: + case ITEMS: + return this.myGridCache.getItemInventoryHandler(); + case FLUIDS: + return this.myGridCache.getFluidInventoryHandler(); + default: } return null; } + @Override + protected void postChangesToListeners( Iterable changes, BaseActionSource src ) + { + this.postChange( true, changes, src ); + } + + protected void postChange( boolean Add, Iterable changes, BaseActionSource src ) + { + if( DEPTH.contains( this ) ) + return; + + DEPTH.push( this ); + + this.sendEvent = true; + this.notifyListenersOfChange( changes, src ); + + IItemList myStorageList = this.getStorageList(); + + for( T changedItem : changes ) + { + T difference = changedItem; + + if( !Add && changedItem != null ) + ( difference = changedItem.copy() ).setStackSize( -changedItem.getStackSize() ); + + if( this.myGridCache.interestManager.containsKey( changedItem ) ) + { + Collection list = this.myGridCache.interestManager.get( changedItem ); + if( !list.isEmpty() ) + { + IAEStack fullStack = myStorageList.findPrecise( changedItem ); + if( fullStack == null ) + { + fullStack = changedItem.copy(); + fullStack.setStackSize( 0 ); + } + + this.myGridCache.interestManager.enableTransactions(); + + for( ItemWatcher iw : list ) + iw.getHost().onStackChange( myStorageList, fullStack, difference, src, this.getChannel() ); + + this.myGridCache.interestManager.disableTransactions(); + } + } + } + + final NetworkMonitor last = DEPTH.pop(); + if( last != this ) + throw new RuntimeException( "Invalid Access to Networked Storage API detected." ); + } } diff --git a/src/main/java/appeng/me/cache/P2PCache.java b/src/main/java/appeng/me/cache/P2PCache.java index 236f96db1..75c489349 100644 --- a/src/main/java/appeng/me/cache/P2PCache.java +++ b/src/main/java/appeng/me/cache/P2PCache.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.HashMap; import com.google.common.collect.LinkedHashMultimap; @@ -37,37 +38,38 @@ import appeng.me.cache.helpers.TunnelCollection; import appeng.parts.p2p.PartP2PTunnel; import appeng.parts.p2p.PartP2PTunnelME; + public class P2PCache implements IGridCache { + final IGrid myGrid; final private HashMap inputs = new HashMap(); final private Multimap outputs = LinkedHashMultimap.create(); final private TunnelCollection NullColl = new TunnelCollection( null, null ); - final IGrid myGrid; - - public P2PCache(IGrid g) { + public P2PCache( IGrid g ) + { this.myGrid = g; } @MENetworkEventSubscribe - public void bootComplete(MENetworkBootingStatusChange bootStatus) + public void bootComplete( MENetworkBootingStatusChange bootStatus ) { ITickManager tm = this.myGrid.getCache( ITickManager.class ); - for (PartP2PTunnel me : this.inputs.values()) + for( PartP2PTunnel me : this.inputs.values() ) { - if ( me instanceof PartP2PTunnelME ) + if( me instanceof PartP2PTunnelME ) tm.wakeDevice( me.getGridNode() ); } } @MENetworkEventSubscribe - public void bootComplete(MENetworkPowerStatusChange power) + public void bootComplete( MENetworkPowerStatusChange power ) { ITickManager tm = this.myGrid.getCache( ITickManager.class ); - for (PartP2PTunnel me : this.inputs.values()) + for( PartP2PTunnel me : this.inputs.values() ) { - if ( me instanceof PartP2PTunnelME ) + if( me instanceof PartP2PTunnelME ) tm.wakeDevice( me.getGridNode() ); } } @@ -78,17 +80,101 @@ public class P2PCache implements IGridCache } - public void updateFreq(PartP2PTunnel t, long NewFreq) + @Override + public void removeNode( IGridNode node, IGridHost machine ) { - if ( this.outputs.containsValue( t ) ) + if( machine instanceof PartP2PTunnel ) + { + if( machine instanceof PartP2PTunnelME ) + { + if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) + return; + } + + PartP2PTunnel t = (PartP2PTunnel) machine; + // AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq + // ); + + if( t.output ) + this.outputs.remove( t.freq, t ); + else + this.inputs.remove( t.freq ); + + this.updateTunnel( t.freq, !t.output, false ); + } + } + + @Override + public void addNode( IGridNode node, IGridHost machine ) + { + if( machine instanceof PartP2PTunnel ) + { + if( machine instanceof PartP2PTunnelME ) + { + if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) + return; + } + + PartP2PTunnel t = (PartP2PTunnel) machine; + // AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq + // ); + + if( t.output ) + this.outputs.put( t.freq, t ); + else + this.inputs.put( t.freq, t ); + + this.updateTunnel( t.freq, !t.output, false ); + } + } + + @Override + public void onSplit( IGridStorage storageB ) + { + + } + + @Override + public void onJoin( IGridStorage storageB ) + { + + } + + @Override + public void populateGridStorage( IGridStorage storage ) + { + + } + + private void updateTunnel( long freq, boolean updateOutputs, boolean configChange ) + { + for( PartP2PTunnel p : this.outputs.get( freq ) ) + { + if( configChange ) + p.onTunnelConfigChange(); + p.onTunnelNetworkChange(); + } + + PartP2PTunnel in = this.inputs.get( freq ); + if( in != null ) + { + if( configChange ) + in.onTunnelConfigChange(); + in.onTunnelNetworkChange(); + } + } + + public void updateFreq( PartP2PTunnel t, long NewFreq ) + { + if( this.outputs.containsValue( t ) ) this.outputs.remove( t.freq, t ); - if ( this.inputs.containsValue( t ) ) + if( this.inputs.containsValue( t ) ) this.inputs.remove( t.freq ); t.freq = NewFreq; - if ( t.output ) + if( t.output ) this.outputs.put( t.freq, t ); else this.inputs.put( t.freq, t ); @@ -99,106 +185,21 @@ public class P2PCache implements IGridCache this.updateTunnel( t.freq, !t.output, true ); } - @Override - public void addNode(IGridNode node, IGridHost machine) - { - if ( machine instanceof PartP2PTunnel ) - { - if ( machine instanceof PartP2PTunnelME ) - { - if ( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) - return; - } - - PartP2PTunnel t = (PartP2PTunnel) machine; - // AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq - // ); - - if ( t.output ) - this.outputs.put( t.freq, t ); - else - this.inputs.put( t.freq, t ); - - this.updateTunnel( t.freq, !t.output, false ); - } - } - - @Override - public void removeNode(IGridNode node, IGridHost machine) - { - if ( machine instanceof PartP2PTunnel ) - { - if ( machine instanceof PartP2PTunnelME ) - { - if ( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) - return; - } - - PartP2PTunnel t = (PartP2PTunnel) machine; - // AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq - // ); - - if ( t.output ) - this.outputs.remove( t.freq, t ); - else - this.inputs.remove( t.freq ); - - this.updateTunnel( t.freq, !t.output, false ); - } - } - - private void updateTunnel(long freq, boolean updateOutputs, boolean configChange) - { - for (PartP2PTunnel p : this.outputs.get( freq )) - { - if ( configChange ) - p.onTunnelConfigChange(); - p.onTunnelNetworkChange(); - } - - PartP2PTunnel in = this.inputs.get( freq ); - if ( in != null ) - { - if ( configChange ) - in.onTunnelConfigChange(); - in.onTunnelNetworkChange(); - } - } - - public TunnelCollection getOutputs(long freq, Class c) + public TunnelCollection getOutputs( long freq, Class c ) { PartP2PTunnel in = this.inputs.get( freq ); - if ( in == null ) + if( in == null ) return this.NullColl; TunnelCollection out = this.inputs.get( freq ).getCollection( this.outputs.get( freq ), c ); - if ( out == null ) + if( out == null ) return this.NullColl; return out; } - public PartP2PTunnel getInput(long freq) + public PartP2PTunnel getInput( long freq ) { return this.inputs.get( freq ); } - - @Override - public void onSplit(IGridStorage storageB) - { - - } - - @Override - public void onJoin(IGridStorage storageB) - { - - } - - @Override - public void populateGridStorage(IGridStorage storage) - { - - } - } diff --git a/src/main/java/appeng/me/cache/PathGridCache.java b/src/main/java/appeng/me/cache/PathGridCache.java index 57f562dcf..22b86a2ae 100644 --- a/src/main/java/appeng/me/cache/PathGridCache.java +++ b/src/main/java/appeng/me/cache/PathGridCache.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; @@ -55,34 +56,28 @@ import appeng.me.pathfinding.PathSegment; import appeng.tile.networking.TileController; import appeng.util.Platform; + public class PathGridCache implements IPathingGrid { - boolean recalculateControllerNextTick = true; - boolean updateNetwork = true; - boolean booting = false; - final LinkedList active = new LinkedList(); - - ControllerState controllerState = ControllerState.NO_CONTROLLER; - - int instance = Integer.MIN_VALUE; - - int ticksUntilReady = 20; - public int channelsInUse = 0; - int lastChannels = 0; - final Set controllers = new HashSet(); final Set requireChannels = new HashSet(); final Set blockDense = new HashSet(); - final IGrid myGrid; - private HashSet semiOpen = new HashSet(); - + public int channelsInUse = 0; public int channelsByBlocks = 0; public double channelPowerUsage = 0.0; + boolean recalculateControllerNextTick = true; + boolean updateNetwork = true; + boolean booting = false; + ControllerState controllerState = ControllerState.NO_CONTROLLER; + int instance = Integer.MIN_VALUE; + int ticksUntilReady = 20; + int lastChannels = 0; + private HashSet semiOpen = new HashSet(); - public PathGridCache(IGrid g) + public PathGridCache( IGrid g ) { this.myGrid = g; } @@ -90,14 +85,14 @@ public class PathGridCache implements IPathingGrid @Override public void onUpdateTick() { - if ( this.recalculateControllerNextTick ) + if( this.recalculateControllerNextTick ) { this.recalcController(); } - if ( this.updateNetwork ) + if( this.updateNetwork ) { - if ( !this.booting ) + if( !this.booting ) this.myGrid.postEvent( new MENetworkBootingStatusChange() ); this.booting = true; @@ -105,7 +100,7 @@ public class PathGridCache implements IPathingGrid this.instance++; this.channelsInUse = 0; - if ( !AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) ) + if( !AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) ) { int used = this.calculateRequiredChannels(); @@ -116,11 +111,11 @@ public class PathGridCache implements IPathingGrid this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( used ) ); } - else if ( this.controllerState == ControllerState.NO_CONTROLLER ) + else if( this.controllerState == ControllerState.NO_CONTROLLER ) { int requiredChannels = this.calculateRequiredChannels(); int used = requiredChannels; - if ( requiredChannels > 8 ) + if( requiredChannels > 8 ) used = 0; int nodes = this.myGrid.getNodes().size(); @@ -132,7 +127,7 @@ public class PathGridCache implements IPathingGrid this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( used ) ); } - else if ( this.controllerState == ControllerState.CONTROLLER_CONFLICT ) + else if( this.controllerState == ControllerState.CONTROLLER_CONFLICT ) { this.ticksUntilReady = 20; this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) ); @@ -146,13 +141,13 @@ public class PathGridCache implements IPathingGrid // myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) // ); - for (IGridNode node : this.myGrid.getMachines( TileController.class )) + for( IGridNode node : this.myGrid.getMachines( TileController.class ) ) { closedList.add( (IPathItem) node ); - for (IGridConnection gcc : node.getConnections()) + for( IGridConnection gcc : node.getConnections() ) { GridConnection gc = (GridConnection) gcc; - if ( !(gc.getOtherSide( node ).getMachine() instanceof TileController) ) + if( !( gc.getOtherSide( node ).getMachine() instanceof TileController ) ) { List open = new LinkedList(); closedList.add( gc ); @@ -165,13 +160,13 @@ public class PathGridCache implements IPathingGrid } } - if ( !this.active.isEmpty() || this.ticksUntilReady > 0 ) + if( !this.active.isEmpty() || this.ticksUntilReady > 0 ) { Iterator i = this.active.iterator(); - while (i.hasNext()) + while( i.hasNext() ) { PathSegment pat = i.next(); - if ( pat.step() ) + if( pat.step() ) { pat.isDead = true; i.remove(); @@ -180,12 +175,12 @@ public class PathGridCache implements IPathingGrid this.ticksUntilReady--; - if ( this.active.isEmpty() && this.ticksUntilReady <= 0 ) + if( this.active.isEmpty() && this.ticksUntilReady <= 0 ) { - if ( this.controllerState == ControllerState.CONTROLLER_ONLINE ) + if( this.controllerState == ControllerState.CONTROLLER_ONLINE ) { final Iterator controllerIterator = this.controllers.iterator(); - if (controllerIterator.hasNext()) + if( controllerIterator.hasNext() ) { final TileController controller = controllerIterator.next(); controller.getGridNode( ForgeDirection.UNKNOWN ).beginVisit( new ControllerChannelUpdater() ); @@ -202,19 +197,142 @@ public class PathGridCache implements IPathingGrid } } + @Override + public void removeNode( IGridNode gridNode, IGridHost machine ) + { + if( machine instanceof TileController ) + { + this.controllers.remove( machine ); + this.recalculateControllerNextTick = true; + } + + EnumSet flags = gridNode.getGridBlock().getFlags(); + + if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) + this.requireChannels.remove( gridNode ); + + if( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) + this.blockDense.remove( gridNode ); + + this.repath(); + } + + @Override + public void addNode( IGridNode gridNode, IGridHost machine ) + { + if( machine instanceof TileController ) + { + this.controllers.add( (TileController) machine ); + this.recalculateControllerNextTick = true; + } + + EnumSet flags = gridNode.getGridBlock().getFlags(); + + if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) + this.requireChannels.add( gridNode ); + + if( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) + this.blockDense.add( gridNode ); + + this.repath(); + } + + @Override + public void onSplit( IGridStorage storageB ) + { + + } + + @Override + public void onJoin( IGridStorage storageB ) + { + + } + + @Override + public void populateGridStorage( IGridStorage storage ) + { + + } + + private void recalcController() + { + this.recalculateControllerNextTick = false; + ControllerState old = this.controllerState; + + if( this.controllers.isEmpty() ) + { + this.controllerState = ControllerState.NO_CONTROLLER; + } + else + { + IGridNode startingNode = this.controllers.iterator().next().getGridNode( ForgeDirection.UNKNOWN ); + if( startingNode == null ) + { + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + return; + } + + DimensionalCoord dc = startingNode.getGridBlock().getLocation(); + ControllerValidator cv = new ControllerValidator( dc.x, dc.y, dc.z ); + + startingNode.beginVisit( cv ); + + if( cv.isValid && cv.found == this.controllers.size() ) + this.controllerState = ControllerState.CONTROLLER_ONLINE; + else + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + } + + if( old != this.controllerState ) + { + this.myGrid.postEvent( new MENetworkControllerChange() ); + } + } + + private int calculateRequiredChannels() + { + int depth = 0; + this.semiOpen.clear(); + + for( IGridNode nodes : this.requireChannels ) + { + if( !this.semiOpen.contains( nodes ) ) + { + IGridBlock gb = nodes.getGridBlock(); + EnumSet flags = gb.getFlags(); + + if( flags.contains( GridFlags.COMPRESSED_CHANNEL ) && !this.blockDense.isEmpty() ) + return 9; + + depth++; + + if( flags.contains( GridFlags.MULTIBLOCK ) ) + { + IGridMultiblock gmb = (IGridMultiblock) gb; + Iterator i = gmb.getMultiblockNodes(); + while( i.hasNext() ) + this.semiOpen.add( (IPathItem) i.next() ); + } + } + } + + return depth; + } + private void achievementPost() { - if ( this.lastChannels != this.channelsInUse && AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) ) + if( this.lastChannels != this.channelsInUse && AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) ) { Achievements currentBracket = this.getAchievementBracket( this.channelsInUse ); Achievements lastBracket = this.getAchievementBracket( this.lastChannels ); - if ( currentBracket != lastBracket && currentBracket != null ) + if( currentBracket != lastBracket && currentBracket != null ) { Set players = new HashSet(); - for (IGridNode n : this.requireChannels) + for( IGridNode n : this.requireChannels ) players.add( n.getPlayerID() ); - for (int id : players) + for( int id : players ) { Platform.addStat( id, currentBracket.getAchievement() ); } @@ -223,48 +341,43 @@ public class PathGridCache implements IPathingGrid this.lastChannels = this.channelsInUse; } - private Achievements getAchievementBracket(int ch) + private Achievements getAchievementBracket( int ch ) { - if ( ch < 8 ) + if( ch < 8 ) return null; - if ( ch < 128 ) + if( ch < 128 ) return Achievements.Networking1; - if ( ch < 2048 ) + if( ch < 2048 ) return Achievements.Networking2; return Achievements.Networking3; } - private int calculateRequiredChannels() + @MENetworkEventSubscribe + void updateNodReq( MENetworkChannelChanged ev ) { - int depth = 0; - this.semiOpen.clear(); + IGridNode gridNode = ev.node; - for (IGridNode nodes : this.requireChannels) - { - if ( !this.semiOpen.contains( nodes ) ) - { - IGridBlock gb = nodes.getGridBlock(); - EnumSet flags = gb.getFlags(); + if( gridNode.getGridBlock().getFlags().contains( GridFlags.REQUIRE_CHANNEL ) ) + this.requireChannels.add( gridNode ); + else + this.requireChannels.remove( gridNode ); - if ( flags.contains( GridFlags.COMPRESSED_CHANNEL ) && !this.blockDense.isEmpty() ) - return 9; + this.repath(); + } - depth++; + @Override + public boolean isNetworkBooting() + { + return !this.active.isEmpty() && !this.booting; + } - if ( flags.contains( GridFlags.MULTIBLOCK ) ) - { - IGridMultiblock gmb = (IGridMultiblock) gb; - Iterator i = gmb.getMultiblockNodes(); - while (i.hasNext()) - this.semiOpen.add( (IPathItem) i.next() ); - } - } - } - - return depth; + @Override + public ControllerState getControllerState() + { + return this.controllerState; } @Override @@ -276,123 +389,4 @@ public class PathGridCache implements IPathingGrid this.channelsByBlocks = 0; this.updateNetwork = true; } - - @Override - public void removeNode(IGridNode gridNode, IGridHost machine) - { - if ( machine instanceof TileController ) - { - this.controllers.remove( machine ); - this.recalculateControllerNextTick = true; - } - - EnumSet flags = gridNode.getGridBlock().getFlags(); - - if ( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) - this.requireChannels.remove( gridNode ); - - if ( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) - this.blockDense.remove( gridNode ); - - this.repath(); - } - - @Override - public void addNode(IGridNode gridNode, IGridHost machine) - { - if ( machine instanceof TileController ) - { - this.controllers.add( (TileController) machine ); - this.recalculateControllerNextTick = true; - } - - EnumSet flags = gridNode.getGridBlock().getFlags(); - - if ( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) - this.requireChannels.add( gridNode ); - - if ( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) - this.blockDense.add( gridNode ); - - this.repath(); - } - - @MENetworkEventSubscribe - void updateNodReq(MENetworkChannelChanged ev) - { - IGridNode gridNode = ev.node; - - if ( gridNode.getGridBlock().getFlags().contains( GridFlags.REQUIRE_CHANNEL ) ) - this.requireChannels.add( gridNode ); - else - this.requireChannels.remove( gridNode ); - - this.repath(); - } - - private void recalcController() - { - this.recalculateControllerNextTick = false; - ControllerState old = this.controllerState; - - if ( this.controllers.isEmpty() ) - { - this.controllerState = ControllerState.NO_CONTROLLER; - } - else - { - IGridNode startingNode = this.controllers.iterator().next().getGridNode( ForgeDirection.UNKNOWN ); - if ( startingNode == null ) - { - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - return; - } - - DimensionalCoord dc = startingNode.getGridBlock().getLocation(); - ControllerValidator cv = new ControllerValidator( dc.x, dc.y, dc.z ); - - startingNode.beginVisit( cv ); - - if ( cv.isValid && cv.found == this.controllers.size() ) - this.controllerState = ControllerState.CONTROLLER_ONLINE; - else - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - } - - if ( old != this.controllerState ) - { - this.myGrid.postEvent( new MENetworkControllerChange() ); - } - } - - @Override - public ControllerState getControllerState() - { - return this.controllerState; - } - - @Override - public boolean isNetworkBooting() - { - return !this.active.isEmpty() && !this.booting; - } - - @Override - public void onSplit(IGridStorage storageB) - { - - } - - @Override - public void onJoin(IGridStorage storageB) - { - - } - - @Override - public void populateGridStorage(IGridStorage storage) - { - - } - } diff --git a/src/main/java/appeng/me/cache/SecurityCache.java b/src/main/java/appeng/me/cache/SecurityCache.java index c8c3656c0..3cf6cbf5a 100644 --- a/src/main/java/appeng/me/cache/SecurityCache.java +++ b/src/main/java/appeng/me/cache/SecurityCache.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; @@ -37,24 +38,25 @@ import appeng.api.networking.security.ISecurityProvider; import appeng.core.WorldSettings; import appeng.me.GridNode; + public class SecurityCache implements ISecurityGrid { + public final IGrid myGrid; final private List securityProvider = new ArrayList(); final private HashMap> playerPerms = new HashMap>(); + private long securityKey = -1; - public SecurityCache(IGrid g) { + public SecurityCache( IGrid g ) + { this.myGrid = g; } - private long securityKey = -1; - public final IGrid myGrid; - @MENetworkEventSubscribe - public void updatePermissions(MENetworkSecurityChange ev) + public void updatePermissions( MENetworkSecurityChange ev ) { this.playerPerms.clear(); - if ( this.securityProvider.isEmpty() ) + if( this.securityProvider.isEmpty() ) return; this.securityProvider.get( 0 ).readPermissions( this.playerPerms ); @@ -66,27 +68,90 @@ public class SecurityCache implements ISecurityGrid } @Override + public void onUpdateTick() + { + + } + + @Override + public void removeNode( IGridNode gridNode, IGridHost machine ) + { + if( machine instanceof ISecurityProvider ) + { + this.securityProvider.remove( machine ); + this.updateSecurityKey(); + } + } + + private void updateSecurityKey() + { + long lastCode = this.securityKey; + + if( this.securityProvider.size() == 1 ) + this.securityKey = this.securityProvider.get( 0 ).getSecurityKey(); + else + this.securityKey = -1; + + if( lastCode != this.securityKey ) + { + this.myGrid.postEvent( new MENetworkSecurityChange() ); + for( IGridNode n : this.myGrid.getNodes() ) + ( (GridNode) n ).lastSecurityKey = this.securityKey; + } + } + + @Override + public void addNode( IGridNode gridNode, IGridHost machine ) + { + if( machine instanceof ISecurityProvider ) + { + this.securityProvider.add( (ISecurityProvider) machine ); + this.updateSecurityKey(); + } + else + ( (GridNode) gridNode ).lastSecurityKey = this.securityKey; + } + + @Override + public void onSplit( IGridStorage destinationStorage ) + { + + } + + @Override + public void onJoin( IGridStorage sourceStorage ) + { + + } + + @Override + public void populateGridStorage( IGridStorage destinationStorage ) + { + + } @Override public boolean isAvailable() { return this.securityProvider.size() == 1 && this.securityProvider.get( 0 ).isSecurityEnabled(); } + + @Override - public boolean hasPermission(EntityPlayer player, SecurityPermissions perm) + public boolean hasPermission( EntityPlayer player, SecurityPermissions perm ) { return this.hasPermission( player == null ? -1 : WorldSettings.getInstance().getPlayerID( player.getGameProfile() ), perm ); } @Override - public boolean hasPermission(int playerID, SecurityPermissions perm) + public boolean hasPermission( int playerID, SecurityPermissions perm ) { - if ( this.isAvailable() ) + if( this.isAvailable() ) { EnumSet perms = this.playerPerms.get( playerID ); - if ( perms == null ) + if( perms == null ) { - if ( playerID == -1 ) // no default? + if( playerID == -1 ) // no default? return false; else return this.hasPermission( -1, perm ); @@ -97,75 +162,11 @@ public class SecurityCache implements ISecurityGrid return true; } - private void updateSecurityKey() - { - long lastCode = this.securityKey; - - if ( this.securityProvider.size() == 1 ) - this.securityKey = this.securityProvider.get( 0 ).getSecurityKey(); - else - this.securityKey = -1; - - if ( lastCode != this.securityKey ) - { - this.myGrid.postEvent( new MENetworkSecurityChange() ); - for (IGridNode n : this.myGrid.getNodes()) - ((GridNode) n).lastSecurityKey = this.securityKey; - } - } - - @Override - public void removeNode(IGridNode gridNode, IGridHost machine) - { - if ( machine instanceof ISecurityProvider ) - { - this.securityProvider.remove( machine ); - this.updateSecurityKey(); - } - } - - @Override - public void addNode(IGridNode gridNode, IGridHost machine) - { - if ( machine instanceof ISecurityProvider ) - { - this.securityProvider.add( (ISecurityProvider) machine ); - this.updateSecurityKey(); - } - else - ((GridNode) gridNode).lastSecurityKey = this.securityKey; - } - - @Override - public void onUpdateTick() - { - - } - - @Override - public void onSplit(IGridStorage destinationStorage) - { - - } - - @Override - public void onJoin(IGridStorage sourceStorage) - { - - } - - @Override - public void populateGridStorage(IGridStorage destinationStorage) - { - - } - @Override public int getOwner() { - if ( this.isAvailable() ) + if( this.isAvailable() ) return this.securityProvider.get( 0 ).getOwner(); return -1; } - } diff --git a/src/main/java/appeng/me/cache/SpatialPylonCache.java b/src/main/java/appeng/me/cache/SpatialPylonCache.java index 9e98a7902..40894b31f 100644 --- a/src/main/java/appeng/me/cache/SpatialPylonCache.java +++ b/src/main/java/appeng/me/cache/SpatialPylonCache.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -36,31 +37,138 @@ import appeng.me.cluster.implementations.SpatialPylonCluster; import appeng.tile.spatial.TileSpatialIOPort; import appeng.tile.spatial.TileSpatialPylon; + public class SpatialPylonCache implements ISpatialCache { + final IGrid myGrid; long powerRequired = 0; double efficiency = 0.0; - DimensionalCoord captureMin; DimensionalCoord captureMax; boolean isValid = false; - List ioPorts = new LinkedList(); HashMap clusters = new HashMap(); - boolean needsUpdate = false; - final IGrid myGrid; - - public SpatialPylonCache(IGrid g) { + public SpatialPylonCache( IGrid g ) + { this.myGrid = g; } - @Override - public long requiredPower() + @MENetworkEventSubscribe + public void bootingRender( MENetworkBootingStatusChange c ) { - return this.powerRequired; + this.reset( this.myGrid ); + } + + public void reset( IGrid grid ) + { + int reqX = 0; + int reqY = 0; + int reqZ = 0; + int requirePylonBlocks = 1; + + double minPower = 0; + double maxPower = 0; + + this.clusters = new HashMap(); + this.ioPorts = new LinkedList(); + + for( IGridNode gm : grid.getMachines( TileSpatialIOPort.class ) ) + { + this.ioPorts.add( (TileSpatialIOPort) gm.getMachine() ); + } + + IReadOnlyCollection set = grid.getMachines( TileSpatialPylon.class ); + for( IGridNode gm : set ) + { + if( gm.meetsChannelRequirements() ) + { + SpatialPylonCluster c = ( (TileSpatialPylon) gm.getMachine() ).getCluster(); + if( c != null ) + this.clusters.put( c, c ); + } + } + + this.captureMax = null; + this.captureMin = null; + this.isValid = true; + + int pylonBlocks = 0; + for( SpatialPylonCluster cl : this.clusters.values() ) + { + if( this.captureMax == null ) + this.captureMax = cl.max.copy(); + if( this.captureMin == null ) + this.captureMin = cl.min.copy(); + + pylonBlocks += cl.tileCount(); + + this.captureMin.x = Math.min( this.captureMin.x, cl.min.x ); + this.captureMin.y = Math.min( this.captureMin.y, cl.min.y ); + this.captureMin.z = Math.min( this.captureMin.z, cl.min.z ); + + this.captureMax.x = Math.max( this.captureMax.x, cl.max.x ); + this.captureMax.y = Math.max( this.captureMax.y, cl.max.y ); + this.captureMax.z = Math.max( this.captureMax.z, cl.max.z ); + } + + if( this.hasRegion() ) + { + this.isValid = this.captureMax.x - this.captureMin.x > 1 && this.captureMax.y - this.captureMin.y > 1 && this.captureMax.z - this.captureMin.z > 1; + + for( SpatialPylonCluster cl : this.clusters.values() ) + { + switch( cl.currentAxis ) + { + case X: + + this.isValid = this.isValid && ( ( this.captureMax.y == cl.min.y || this.captureMin.y == cl.max.y ) || ( this.captureMax.z == cl.min.z || this.captureMin.z == cl.max.z ) ) && ( ( this.captureMax.y == cl.max.y || this.captureMin.y == cl.min.y ) || ( this.captureMax.z == cl.max.z || this.captureMin.z == cl.min.z ) ); + + break; + case Y: + + this.isValid = this.isValid && ( ( this.captureMax.x == cl.min.x || this.captureMin.x == cl.max.x ) || ( this.captureMax.z == cl.min.z || this.captureMin.z == cl.max.z ) ) && ( ( this.captureMax.x == cl.max.x || this.captureMin.x == cl.min.x ) || ( this.captureMax.z == cl.max.z || this.captureMin.z == cl.min.z ) ); + + break; + case Z: + + this.isValid = this.isValid && ( ( this.captureMax.y == cl.min.y || this.captureMin.y == cl.max.y ) || ( this.captureMax.x == cl.min.x || this.captureMin.x == cl.max.x ) ) && ( ( this.captureMax.y == cl.max.y || this.captureMin.y == cl.min.y ) || ( this.captureMax.x == cl.max.x || this.captureMin.x == cl.min.x ) ); + + break; + case UNFORMED: + this.isValid = false; + break; + } + } + + reqX = this.captureMax.x - this.captureMin.x; + reqY = this.captureMax.y - this.captureMin.y; + reqZ = this.captureMax.z - this.captureMin.z; + requirePylonBlocks = Math.max( 6, ( ( reqX * reqZ + reqX * reqY + reqY * reqZ ) * 3 ) / 8 ); + + this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks; + + if( this.efficiency > 1.0 ) + this.efficiency = 1.0; + if( this.efficiency < 0.0 ) + this.efficiency = 0.0; + + minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance.spatialPowerMultiplier; + maxPower = Math.pow( minPower, AEConfig.instance.spatialPowerExponent ); + } + + double affective_efficiency = Math.pow( this.efficiency, 0.25 ); + this.powerRequired = (long) ( affective_efficiency * minPower + ( 1.0 - affective_efficiency ) * maxPower ); + + for( SpatialPylonCluster cl : this.clusters.values() ) + { + boolean myWasValid = cl.isValid; + cl.isValid = this.isValid; + if( myWasValid != this.isValid ) + cl.updateStatus( false ); + } } @Override @@ -87,116 +195,10 @@ public class SpatialPylonCache implements ISpatialCache return this.captureMax; } - public void reset(IGrid grid) + @Override + public long requiredPower() { - int reqX = 0; - int reqY = 0; - int reqZ = 0; - int requirePylonBlocks = 1; - - double minPower = 0; - double maxPower = 0; - - this.clusters = new HashMap(); - this.ioPorts = new LinkedList(); - - for (IGridNode gm : grid.getMachines( TileSpatialIOPort.class )) - { - this.ioPorts.add( (TileSpatialIOPort) gm.getMachine() ); - } - - IReadOnlyCollection set = grid.getMachines( TileSpatialPylon.class ); - for (IGridNode gm : set) - { - if ( gm.meetsChannelRequirements() ) - { - SpatialPylonCluster c = ((TileSpatialPylon) gm.getMachine()).getCluster(); - if ( c != null ) - this.clusters.put( c, c ); - } - } - - this.captureMax = null; - this.captureMin = null; - this.isValid = true; - - int pylonBlocks = 0; - for (SpatialPylonCluster cl : this.clusters.values()) - { - if ( this.captureMax == null ) - this.captureMax = cl.max.copy(); - if ( this.captureMin == null ) - this.captureMin = cl.min.copy(); - - pylonBlocks += cl.tileCount(); - - this.captureMin.x = Math.min( this.captureMin.x, cl.min.x ); - this.captureMin.y = Math.min( this.captureMin.y, cl.min.y ); - this.captureMin.z = Math.min( this.captureMin.z, cl.min.z ); - - this.captureMax.x = Math.max( this.captureMax.x, cl.max.x ); - this.captureMax.y = Math.max( this.captureMax.y, cl.max.y ); - this.captureMax.z = Math.max( this.captureMax.z, cl.max.z ); - } - - if ( this.hasRegion() ) - { - this.isValid = this.captureMax.x - this.captureMin.x > 1 && this.captureMax.y - this.captureMin.y > 1 && this.captureMax.z - this.captureMin.z > 1; - - for (SpatialPylonCluster cl : this.clusters.values()) - { - switch (cl.currentAxis) - { - case X: - - this.isValid = this.isValid && ((this.captureMax.y == cl.min.y || this.captureMin.y == cl.max.y) || (this.captureMax.z == cl.min.z || this.captureMin.z == cl.max.z)) - && ((this.captureMax.y == cl.max.y || this.captureMin.y == cl.min.y) || (this.captureMax.z == cl.max.z || this.captureMin.z == cl.min.z)); - - break; - case Y: - - this.isValid = this.isValid && ((this.captureMax.x == cl.min.x || this.captureMin.x == cl.max.x) || (this.captureMax.z == cl.min.z || this.captureMin.z == cl.max.z)) - && ((this.captureMax.x == cl.max.x || this.captureMin.x == cl.min.x) || (this.captureMax.z == cl.max.z || this.captureMin.z == cl.min.z)); - - break; - case Z: - - this.isValid = this.isValid && ((this.captureMax.y == cl.min.y || this.captureMin.y == cl.max.y) || (this.captureMax.x == cl.min.x || this.captureMin.x == cl.max.x)) - && ((this.captureMax.y == cl.max.y || this.captureMin.y == cl.min.y) || (this.captureMax.x == cl.max.x || this.captureMin.x == cl.min.x)); - - break; - case UNFORMED: - this.isValid = false; - break; - } - } - - reqX = this.captureMax.x - this.captureMin.x; - reqY = this.captureMax.y - this.captureMin.y; - reqZ = this.captureMax.z - this.captureMin.z; - requirePylonBlocks = Math.max( 6, ((reqX * reqZ + reqX * reqY + reqY * reqZ) * 3) / 8 ); - - this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks; - - if ( this.efficiency > 1.0 ) - this.efficiency = 1.0; - if ( this.efficiency < 0.0 ) - this.efficiency = 0.0; - - minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance.spatialPowerMultiplier; - maxPower = Math.pow( minPower, AEConfig.instance.spatialPowerExponent ); - } - - double affective_efficiency = Math.pow( this.efficiency, 0.25 ); - this.powerRequired = (long) (affective_efficiency * minPower + (1.0 - affective_efficiency) * maxPower); - - for (SpatialPylonCluster cl : this.clusters.values()) - { - boolean myWasValid = cl.isValid; - cl.isValid = this.isValid; - if ( myWasValid != this.isValid ) - cl.updateStatus( false ); - } + return this.powerRequired; } @Override @@ -205,45 +207,38 @@ public class SpatialPylonCache implements ISpatialCache return (float) this.efficiency * 100; } - @MENetworkEventSubscribe - public void bootingRender(MENetworkBootingStatusChange c) - { - this.reset( this.myGrid ); - } - @Override public void onUpdateTick() { } @Override - public void addNode(IGridNode node, IGridHost machine) + public void removeNode( IGridNode node, IGridHost machine ) { } @Override - public void removeNode(IGridNode node, IGridHost machine) + public void addNode( IGridNode node, IGridHost machine ) { } @Override - public void onSplit(IGridStorage storageB) + public void onSplit( IGridStorage storageB ) { } @Override - public void onJoin(IGridStorage storageB) + public void onJoin( IGridStorage storageB ) { } @Override - public void populateGridStorage(IGridStorage storage) + public void populateGridStorage( IGridStorage storage ) { } - } diff --git a/src/main/java/appeng/me/cache/TickManagerCache.java b/src/main/java/appeng/me/cache/TickManagerCache.java index 5b7299d31..c4c017aa1 100644 --- a/src/main/java/appeng/me/cache/TickManagerCache.java +++ b/src/main/java/appeng/me/cache/TickManagerCache.java @@ -18,6 +18,7 @@ package appeng.me.cache; + import java.util.HashMap; import java.util.PriorityQueue; @@ -35,37 +36,35 @@ import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickingRequest; import appeng.me.cache.helpers.TickTracker; + public class TickManagerCache implements ITickManager { - private long currentTick = 0; - final IGrid myGrid; - - public TickManagerCache(IGrid g) { - this.myGrid = g; - } - final HashMap alertable = new HashMap(); - final HashMap sleeping = new HashMap(); final HashMap awake = new HashMap(); - final PriorityQueue upcomingTicks = new PriorityQueue(); + private long currentTick = 0; + + public TickManagerCache( IGrid g ) + { + this.myGrid = g; + } public long getCurrentTick() { return this.currentTick; } - public long getAvgNanoTime(IGridNode node) + public long getAvgNanoTime( IGridNode node ) { TickTracker tt = this.awake.get( node ); - if ( tt == null ) + if( tt == null ) tt = this.sleeping.get( node ); - if ( tt == null ) + if( tt == null ) return -1; return tt.getAvgNanos(); @@ -78,40 +77,40 @@ public class TickManagerCache implements ITickManager try { this.currentTick++; - while (!this.upcomingTicks.isEmpty()) + while( !this.upcomingTicks.isEmpty() ) { tt = this.upcomingTicks.peek(); - int diff = (int) (this.currentTick - tt.lastTick); - if ( diff >= tt.current_rate ) + int diff = (int) ( this.currentTick - tt.lastTick ); + if( diff >= tt.current_rate ) { // remove tt.. this.upcomingTicks.poll(); TickRateModulation mod = tt.gt.tickingRequest( tt.node, diff ); - switch (mod) + switch( mod ) { - case FASTER: - tt.setRate( tt.current_rate - 2 ); - break; - case IDLE: - tt.setRate( tt.request.maxTickRate ); - break; - case SAME: - break; - case SLEEP: - this.sleepDevice( tt.node ); - break; - case SLOWER: - tt.setRate( tt.current_rate + 1 ); - break; - case URGENT: - tt.setRate( 0 ); - break; - default: - break; + case FASTER: + tt.setRate( tt.current_rate - 2 ); + break; + case IDLE: + tt.setRate( tt.request.maxTickRate ); + break; + case SAME: + break; + case SLEEP: + this.sleepDevice( tt.node ); + break; + case SLOWER: + tt.setRate( tt.current_rate + 1 ); + break; + case URGENT: + tt.setRate( 0 ); + break; + default: + break; } - if ( this.awake.containsKey( tt.node ) ) + if( this.awake.containsKey( tt.node ) ) this.addToQueue( tt ); } else @@ -120,24 +119,77 @@ public class TickManagerCache implements ITickManager } catch( Throwable t ) { - CrashReport crashreport = CrashReport.makeCrashReport(t, "Ticking GridNode"); - CrashReportCategory crashreportcategory = crashreport.makeCategory( tt.gt.getClass().getSimpleName() + " being ticked." ); - tt.addEntityCrashInfo(crashreportcategory); - throw new ReportedException(crashreport); + CrashReport crashreport = CrashReport.makeCrashReport( t, "Ticking GridNode" ); + CrashReportCategory crashreportcategory = crashreport.makeCategory( tt.gt.getClass().getSimpleName() + " being ticked." ); + tt.addEntityCrashInfo( crashreportcategory ); + throw new ReportedException( crashreport ); } } - private void addToQueue(TickTracker tt) + private void addToQueue( TickTracker tt ) { tt.lastTick = this.currentTick; this.upcomingTicks.add( tt ); } @Override - public boolean alertDevice(IGridNode node) + public void removeNode( IGridNode gridNode, IGridHost machine ) + { + if( machine instanceof IGridTickable ) + { + this.alertable.remove( gridNode ); + this.sleeping.remove( gridNode ); + this.awake.remove( gridNode ); + } + } + + @Override + public void addNode( IGridNode gridNode, IGridHost machine ) + { + if( machine instanceof IGridTickable ) + { + TickingRequest tr = ( (IGridTickable) machine ).getTickingRequest( gridNode ); + if( tr != null ) + { + TickTracker tt = new TickTracker( tr, gridNode, (IGridTickable) machine, this.currentTick, this ); + + if( tr.canBeAlerted ) + this.alertable.put( gridNode, tt ); + + if( tr.isSleeping ) + this.sleeping.put( gridNode, tt ); + else + { + this.awake.put( gridNode, tt ); + this.addToQueue( tt ); + } + } + } + } + + @Override + public void onSplit( IGridStorage storageB ) + { + + } + + @Override + public void onJoin( IGridStorage storageB ) + { + + } + + @Override + public void populateGridStorage( IGridStorage storage ) + { + + } + + @Override + public boolean alertDevice( IGridNode node ) { TickTracker tt = this.alertable.get( node ); - if ( tt == null ) + if( tt == null ) return false; // throw new RuntimeException( // "Invalid alerted device, this node is not marked as alertable, or part of this grid." ); @@ -158,9 +210,9 @@ public class TickManagerCache implements ITickManager } @Override - public boolean sleepDevice(IGridNode node) + public boolean sleepDevice( IGridNode node ) { - if ( this.awake.containsKey( node ) ) + if( this.awake.containsKey( node ) ) { TickTracker gt = this.awake.get( node ); this.awake.remove( node ); @@ -173,9 +225,9 @@ public class TickManagerCache implements ITickManager } @Override - public boolean wakeDevice(IGridNode node) + public boolean wakeDevice( IGridNode node ) { - if ( this.sleeping.containsKey( node ) ) + if( this.sleeping.containsKey( node ) ) { TickTracker gt = this.sleeping.get( node ); this.sleeping.remove( node ); @@ -187,58 +239,4 @@ public class TickManagerCache implements ITickManager return false; } - - @Override - public void removeNode(IGridNode gridNode, IGridHost machine) - { - if ( machine instanceof IGridTickable ) - { - this.alertable.remove( gridNode ); - this.sleeping.remove( gridNode ); - this.awake.remove( gridNode ); - } - } - - @Override - public void addNode(IGridNode gridNode, IGridHost machine) - { - if ( machine instanceof IGridTickable ) - { - TickingRequest tr = ((IGridTickable) machine).getTickingRequest( gridNode ); - if ( tr != null ) - { - TickTracker tt = new TickTracker( tr, gridNode, (IGridTickable) machine, this.currentTick, this ); - - if ( tr.canBeAlerted ) - this.alertable.put( gridNode, tt ); - - if ( tr.isSleeping ) - this.sleeping.put( gridNode, tt ); - else - { - this.awake.put( gridNode, tt ); - this.addToQueue( tt ); - } - - } - } - } - - @Override - public void onSplit(IGridStorage storageB) - { - - } - - @Override - public void onJoin(IGridStorage storageB) - { - - } - - @Override - public void populateGridStorage(IGridStorage storage) - { - - } } diff --git a/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java b/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java index 95c8662ed..760bf5d91 100644 --- a/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java +++ b/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java @@ -18,15 +18,17 @@ package appeng.me.cache.helpers; + import appeng.api.networking.IGridConnection; + public class ConnectionWrapper { public IGridConnection connection; - public ConnectionWrapper(IGridConnection gc) { + public ConnectionWrapper( IGridConnection gc ) + { this.connection = gc; } - } \ No newline at end of file diff --git a/src/main/java/appeng/me/cache/helpers/Connections.java b/src/main/java/appeng/me/cache/helpers/Connections.java index bad763213..8a4d1cf07 100644 --- a/src/main/java/appeng/me/cache/helpers/Connections.java +++ b/src/main/java/appeng/me/cache/helpers/Connections.java @@ -18,22 +18,24 @@ package appeng.me.cache.helpers; + import java.util.HashMap; import java.util.concurrent.Callable; import appeng.api.networking.IGridNode; import appeng.parts.p2p.PartP2PTunnelME; + public class Connections implements Callable { - final private PartP2PTunnelME me; final public HashMap connections = new HashMap(); - + final private PartP2PTunnelME me; public boolean create = false; public boolean destroy = false; - public Connections(PartP2PTunnelME o) { + public Connections( PartP2PTunnelME o ) + { this.me = o; } @@ -56,5 +58,4 @@ public class Connections implements Callable this.create = true; this.destroy = false; } - } diff --git a/src/main/java/appeng/me/cache/helpers/TickTracker.java b/src/main/java/appeng/me/cache/helpers/TickTracker.java index e4f4db6d3..392a8f949 100644 --- a/src/main/java/appeng/me/cache/helpers/TickTracker.java +++ b/src/main/java/appeng/me/cache/helpers/TickTracker.java @@ -18,6 +18,7 @@ package appeng.me.cache.helpers; + import net.minecraft.crash.CrashReportCategory; import appeng.api.networking.IGridNode; @@ -27,6 +28,7 @@ import appeng.api.util.DimensionalCoord; import appeng.me.cache.TickManagerCache; import appeng.parts.AEBasePart; + public class TickTracker implements Comparable { @@ -40,44 +42,45 @@ public class TickTracker implements Comparable public long lastTick; public int current_rate; - public TickTracker(TickingRequest req, IGridNode node, IGridTickable gt, long currentTick, TickManagerCache tickManagerCache) { + public TickTracker( TickingRequest req, IGridNode node, IGridTickable gt, long currentTick, TickManagerCache tickManagerCache ) + { this.request = req; this.gt = gt; this.node = node; - this.current_rate = (req.minTickRate + req.maxTickRate) / 2; + this.current_rate = ( req.minTickRate + req.maxTickRate ) / 2; this.lastTick = currentTick; this.host = tickManagerCache; } public long getAvgNanos() { - return (this.LastFiveTicksTime / 5); + return ( this.LastFiveTicksTime / 5 ); } - public void setRate(int rate) + public void setRate( int rate ) { this.current_rate = rate; - if ( this.current_rate < this.request.minTickRate ) + if( this.current_rate < this.request.minTickRate ) this.current_rate = this.request.minTickRate; - if ( this.current_rate > this.request.maxTickRate ) + if( this.current_rate > this.request.maxTickRate ) this.current_rate = this.request.maxTickRate; } @Override - public int compareTo(TickTracker t) + public int compareTo( TickTracker t ) { - int nextTick = (int) ((this.lastTick - this.host.getCurrentTick()) + this.current_rate); - int ts_nextTick = (int) ((t.lastTick - this.host.getCurrentTick()) + t.current_rate); + int nextTick = (int) ( ( this.lastTick - this.host.getCurrentTick() ) + this.current_rate ); + int ts_nextTick = (int) ( ( t.lastTick - this.host.getCurrentTick() ) + t.current_rate ); return nextTick - ts_nextTick; } - public void addEntityCrashInfo(CrashReportCategory crashreportcategory) + public void addEntityCrashInfo( CrashReportCategory crashreportcategory ) { - if ( this.gt instanceof AEBasePart ) + if( this.gt instanceof AEBasePart ) { - AEBasePart part = (AEBasePart)this.gt; + AEBasePart part = (AEBasePart) this.gt; part.addEntityCrashInfo( crashreportcategory ); } @@ -89,7 +92,7 @@ public class TickTracker implements Comparable crashreportcategory.addCrashSection( "ConnectedSides", this.node.getConnectedSides() ); DimensionalCoord dc = this.node.getGridBlock().getLocation(); - if ( dc != null ) + if( dc != null ) crashreportcategory.addCrashSection( "Location", dc ); } } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelCollection.java b/src/main/java/appeng/me/cache/helpers/TunnelCollection.java index 70028c6e5..09679a1c7 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelCollection.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelCollection.java @@ -18,32 +18,27 @@ package appeng.me.cache.helpers; + import java.util.Collection; import java.util.Iterator; import appeng.parts.p2p.PartP2PTunnel; import appeng.util.iterators.NullIterator; + public class TunnelCollection implements Iterable { final Class clz; Collection tunnelSources; - public TunnelCollection(Collection src, Class c) { + public TunnelCollection( Collection src, Class c ) + { this.tunnelSources = src; this.clz = c; } - @Override - public Iterator iterator() - { - if ( this.tunnelSources == null ) - return new NullIterator(); - return new TunnelIterator( this.tunnelSources, this.clz ); - } - - public void setSource(Collection c) + public void setSource( Collection c ) { this.tunnelSources = c; } @@ -53,7 +48,15 @@ public class TunnelCollection implements Iterable return !this.iterator().hasNext(); } - public boolean matches(Class c) + @Override + public Iterator iterator() + { + if( this.tunnelSources == null ) + return new NullIterator(); + return new TunnelIterator( this.tunnelSources, this.clz ); + } + + public boolean matches( Class c ) { return this.clz == c; } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelConnection.java b/src/main/java/appeng/me/cache/helpers/TunnelConnection.java index 71c5fb6a0..f626266ad 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelConnection.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelConnection.java @@ -18,16 +18,19 @@ package appeng.me.cache.helpers; + import appeng.api.networking.IGridConnection; import appeng.parts.p2p.PartP2PTunnelME; + public class TunnelConnection { final public PartP2PTunnelME tunnel; final public IGridConnection c; - public TunnelConnection(PartP2PTunnelME t, IGridConnection con) { + public TunnelConnection( PartP2PTunnelME t, IGridConnection con ) + { this.tunnel = t; this.c = con; } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelIterator.java b/src/main/java/appeng/me/cache/helpers/TunnelIterator.java index 4a5ed7f30..620cdf988 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelIterator.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelIterator.java @@ -18,11 +18,13 @@ package appeng.me.cache.helpers; + import java.util.Collection; import java.util.Iterator; import appeng.parts.p2p.PartP2PTunnel; + public class TunnelIterator implements Iterator { @@ -30,22 +32,23 @@ public class TunnelIterator implements Iterator final Class targetType; T Next; - private void findNext() + public TunnelIterator( Collection tunnelSources, Class clz ) { - while (this.Next == null && this.wrapped.hasNext()) - { - this.Next = this.wrapped.next(); - if ( !this.targetType.isInstance( this.Next ) ) - this.Next = null; - } - } - - public TunnelIterator(Collection tunnelSources, Class clz) { this.wrapped = tunnelSources.iterator(); this.targetType = clz; this.findNext(); } + private void findNext() + { + while( this.Next == null && this.wrapped.hasNext() ) + { + this.Next = this.wrapped.next(); + if( !this.targetType.isInstance( this.Next ) ) + this.Next = null; + } + } + @Override public boolean hasNext() { @@ -66,5 +69,4 @@ public class TunnelIterator implements Iterator { // no. } - } diff --git a/src/main/java/appeng/me/cluster/IAECluster.java b/src/main/java/appeng/me/cluster/IAECluster.java index 42642b289..23944f755 100644 --- a/src/main/java/appeng/me/cluster/IAECluster.java +++ b/src/main/java/appeng/me/cluster/IAECluster.java @@ -18,17 +18,18 @@ package appeng.me.cluster; + import java.util.Iterator; import appeng.api.networking.IGridHost; + public interface IAECluster { - void updateStatus(boolean updateGrid); + void updateStatus( boolean updateGrid ); void destroy(); Iterator getTiles(); - } diff --git a/src/main/java/appeng/me/cluster/IAEMultiBlock.java b/src/main/java/appeng/me/cluster/IAEMultiBlock.java index ef85fe515..8dc36f998 100644 --- a/src/main/java/appeng/me/cluster/IAEMultiBlock.java +++ b/src/main/java/appeng/me/cluster/IAEMultiBlock.java @@ -18,14 +18,13 @@ package appeng.me.cluster; + public interface IAEMultiBlock { - void disconnect(boolean b); + void disconnect( boolean b ); IAECluster getCluster(); boolean isValid(); - - } diff --git a/src/main/java/appeng/me/cluster/MBCalculator.java b/src/main/java/appeng/me/cluster/MBCalculator.java index 84a3311f0..cc4b40f66 100644 --- a/src/main/java/appeng/me/cluster/MBCalculator.java +++ b/src/main/java/appeng/me/cluster/MBCalculator.java @@ -18,6 +18,7 @@ package appeng.me.cluster; + import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; @@ -26,65 +27,20 @@ import appeng.api.util.WorldCoord; import appeng.core.AELog; import appeng.util.Platform; + public abstract class MBCalculator { final private IAEMultiBlock target; - public MBCalculator(IAEMultiBlock t) { + public MBCalculator( IAEMultiBlock t ) + { this.target = t; } - /** - * check if the tile entities are correct for the structure. - * - * @param te to be checked tile entity - * @return true if tile entity is valid for structure - */ - public abstract boolean isValidTile(TileEntity te); - - /** - * construct the correct cluster, usually very simple. - * - * @param w world - * @param min min world coord - * @param max max world coord - * @return created cluster - */ - public abstract IAECluster createCluster(World w, WorldCoord min, WorldCoord max); - - /** - * configure the multi-block tiles, most of the important stuff is in here. - * - * @param c updated cluster - * @param w in world - * @param min min world coord - * @param max max world coord - */ - public abstract void updateTiles(IAECluster c, World w, WorldCoord min, WorldCoord max); - - /** - * disassembles the multi-block. - */ - public abstract void disconnect(); - - /** - * verify if the structure is the correct dimensions, or size - * - * @param min min world coord - * @param max max world coord - * @return true if structure has correct dimensions or size - */ - public abstract boolean checkMultiblockScale(WorldCoord min, WorldCoord max); - - public boolean isValidTileAt(World w, int x, int y, int z) + public void calculateMultiblock( World world, WorldCoord loc ) { - return this.isValidTile( w.getTileEntity( x, y, z ) ); - } - - public void calculateMultiblock(World world, WorldCoord loc) - { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; try @@ -93,34 +49,34 @@ public abstract class MBCalculator WorldCoord max = loc.copy(); // find size of MB structure... - while (this.isValidTileAt( world, min.x - 1, min.y, min.z )) + while( this.isValidTileAt( world, min.x - 1, min.y, min.z ) ) min.x--; - while (this.isValidTileAt( world, min.x, min.y - 1, min.z )) + while( this.isValidTileAt( world, min.x, min.y - 1, min.z ) ) min.y--; - while (this.isValidTileAt( world, min.x, min.y, min.z - 1 )) + while( this.isValidTileAt( world, min.x, min.y, min.z - 1 ) ) min.z--; - while (this.isValidTileAt( world, max.x + 1, max.y, max.z )) + while( this.isValidTileAt( world, max.x + 1, max.y, max.z ) ) max.x++; - while (this.isValidTileAt( world, max.x, max.y + 1, max.z )) + while( this.isValidTileAt( world, max.x, max.y + 1, max.z ) ) max.y++; - while (this.isValidTileAt( world, max.x, max.y, max.z + 1 )) + while( this.isValidTileAt( world, max.x, max.y, max.z + 1 ) ) max.z++; - if ( this.checkMultiblockScale( min, max ) ) + if( this.checkMultiblockScale( min, max ) ) { - if ( this.verifyUnownedRegion( world, min, max ) ) + if( this.verifyUnownedRegion( world, min, max ) ) { IAECluster c = this.createCluster( world, min, max ); try { - if ( !this.verifyInternalStructure( world, min, max ) ) + if( !this.verifyInternalStructure( world, min, max ) ) { this.disconnect(); return; } } - catch (Exception err) + catch( Exception err ) { this.disconnect(); return; @@ -128,7 +84,7 @@ public abstract class MBCalculator boolean updateGrid = false; IAECluster cluster = this.target.getCluster(); - if ( cluster == null ) + if( cluster == null ) { this.updateTiles( c, world, min, max ); @@ -142,7 +98,7 @@ public abstract class MBCalculator } } } - catch (Throwable err) + catch( Throwable err ) { AELog.error( err ); } @@ -150,48 +106,107 @@ public abstract class MBCalculator this.disconnect(); } - public abstract boolean verifyInternalStructure(World worldObj, WorldCoord min, WorldCoord max); - - public boolean verifyUnownedRegionInner(World w, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, ForgeDirection side) + public boolean isValidTileAt( World w, int x, int y, int z ) { - switch (side) + return this.isValidTile( w.getTileEntity( x, y, z ) ); + } + + /** + * verify if the structure is the correct dimensions, or size + * + * @param min min world coord + * @param max max world coord + * + * @return true if structure has correct dimensions or size + */ + public abstract boolean checkMultiblockScale( WorldCoord min, WorldCoord max ); + + public boolean verifyUnownedRegion( World w, WorldCoord min, WorldCoord max ) + { + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) + if( this.verifyUnownedRegionInner( w, min.x, min.y, min.z, max.x, max.y, max.z, side ) ) + return false; + + return true; + } + + /** + * construct the correct cluster, usually very simple. + * + * @param w world + * @param min min world coord + * @param max max world coord + * + * @return created cluster + */ + public abstract IAECluster createCluster( World w, WorldCoord min, WorldCoord max ); + + public abstract boolean verifyInternalStructure( World worldObj, WorldCoord min, WorldCoord max ); + + /** + * disassembles the multi-block. + */ + public abstract void disconnect(); + + /** + * configure the multi-block tiles, most of the important stuff is in here. + * + * @param c updated cluster + * @param w in world + * @param min min world coord + * @param max max world coord + */ + public abstract void updateTiles( IAECluster c, World w, WorldCoord min, WorldCoord max ); + + /** + * check if the tile entities are correct for the structure. + * + * @param te to be checked tile entity + * + * @return true if tile entity is valid for structure + */ + public abstract boolean isValidTile( TileEntity te ); + + public boolean verifyUnownedRegionInner( World w, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, ForgeDirection side ) + { + switch( side ) { - case WEST: - minX -= 1; - maxX = minX; - break; - case EAST: - maxX += 1; - minX = maxX; - break; - case DOWN: - minY -= 1; - maxY = minY; - break; - case NORTH: - maxZ += 1; - minZ = maxZ; - break; - case SOUTH: - minZ -= 1; - maxZ = minZ; - break; - case UP: - maxY += 1; - minY = maxY; - break; - case UNKNOWN: - return false; + case WEST: + minX -= 1; + maxX = minX; + break; + case EAST: + maxX += 1; + minX = maxX; + break; + case DOWN: + minY -= 1; + maxY = minY; + break; + case NORTH: + maxZ += 1; + minZ = maxZ; + break; + case SOUTH: + minZ -= 1; + maxZ = minZ; + break; + case UP: + maxY += 1; + minY = maxY; + break; + case UNKNOWN: + return false; } - for (int x = minX; x <= maxX; x++) + for( int x = minX; x <= maxX; x++ ) { - for (int y = minY; y <= maxY; y++) + for( int y = minY; y <= maxY; y++ ) { - for (int z = minZ; z <= maxZ; z++) + for( int z = minZ; z <= maxZ; z++ ) { TileEntity te = w.getTileEntity( x, y, z ); - if ( this.isValidTile( te ) ) + if( this.isValidTile( te ) ) return true; } } @@ -199,14 +214,4 @@ public abstract class MBCalculator return false; } - - public boolean verifyUnownedRegion(World w, WorldCoord min, WorldCoord max) - { - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) - if ( this.verifyUnownedRegionInner( w, min.x, min.y, min.z, max.x, max.y, max.z, side ) ) - return false; - - return true; - } - } diff --git a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java index fb748497a..cda328607 100644 --- a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java @@ -18,6 +18,7 @@ package appeng.me.cluster.implementations; + import java.util.Iterator; import net.minecraft.tileentity.TileEntity; @@ -34,47 +35,80 @@ import appeng.me.cluster.IAEMultiBlock; import appeng.me.cluster.MBCalculator; import appeng.tile.crafting.TileCraftingTile; + public class CraftingCPUCalculator extends MBCalculator { final TileCraftingTile tqb; - public CraftingCPUCalculator(IAEMultiBlock t) { + public CraftingCPUCalculator( IAEMultiBlock t ) + { super( t ); this.tqb = (TileCraftingTile) t; } @Override - public boolean isValidTile(TileEntity te) + public boolean checkMultiblockScale( WorldCoord min, WorldCoord max ) { - return te instanceof TileCraftingTile; - } - - @Override - public boolean checkMultiblockScale(WorldCoord min, WorldCoord max) - { - if ( max.x - min.x > 16 ) + if( max.x - min.x > 16 ) return false; - if ( max.y - min.y > 16 ) + if( max.y - min.y > 16 ) return false; - if ( max.z - min.z > 16 ) + if( max.z - min.z > 16 ) return false; return true; } @Override - public void updateTiles(IAECluster cl, World w, WorldCoord min, WorldCoord max) + public IAECluster createCluster( World w, WorldCoord min, WorldCoord max ) + { + return new CraftingCPUCluster( min, max ); + } + + @Override + public boolean verifyInternalStructure( World w, WorldCoord min, WorldCoord max ) + { + boolean storage = false; + + for( int x = min.x; x <= max.x; x++ ) + { + for( int y = min.y; y <= max.y; y++ ) + { + for( int z = min.z; z <= max.z; z++ ) + { + IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); + + if( !te.isValid() ) + return false; + + if( !storage && te instanceof TileCraftingTile ) + storage = ( (TileCraftingTile) te ).getStorageBytes() > 0; + } + } + } + + return storage; + } + + @Override + public void disconnect() + { + this.tqb.disconnect( true ); + } + + @Override + public void updateTiles( IAECluster cl, World w, WorldCoord min, WorldCoord max ) { CraftingCPUCluster c = (CraftingCPUCluster) cl; - for (int x = min.x; x <= max.x; x++) + for( int x = min.x; x <= max.x; x++ ) { - for (int y = min.y; y <= max.y; y++) + for( int y = min.y; y <= max.y; y++ ) { - for (int z = min.z; z <= max.z; z++) + for( int z = min.z; z <= max.z; z++ ) { TileCraftingTile te = (TileCraftingTile) w.getTileEntity( x, y, z ); te.updateStatus( c ); @@ -86,14 +120,14 @@ public class CraftingCPUCalculator extends MBCalculator c.done(); Iterator i = c.getTiles(); - while (i.hasNext()) + while( i.hasNext() ) { IGridHost gh = i.next(); IGridNode n = gh.getGridNode( ForgeDirection.UNKNOWN ); - if ( n != null ) + if( n != null ) { IGrid g = n.getGrid(); - if ( g != null ) + if( g != null ) { g.postEvent( new MENetworkCraftingCpuChange( n ) ); return; @@ -103,40 +137,8 @@ public class CraftingCPUCalculator extends MBCalculator } @Override - public IAECluster createCluster(World w, WorldCoord min, WorldCoord max) + public boolean isValidTile( TileEntity te ) { - return new CraftingCPUCluster( min, max ); + return te instanceof TileCraftingTile; } - - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } - - @Override - public boolean verifyInternalStructure(World w, WorldCoord min, WorldCoord max) - { - boolean storage = false; - - for (int x = min.x; x <= max.x; x++) - { - for (int y = min.y; y <= max.y; y++) - { - for (int z = min.z; z <= max.z; z++) - { - IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); - - if ( !te.isValid() ) - return false; - - if ( !storage && te instanceof TileCraftingTile ) - storage = ((TileCraftingTile) te).getStorageBytes() > 0; - } - } - } - - return storage; - } - } diff --git a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java index e5acfab71..b91b2c104 100644 --- a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java @@ -79,78 +79,47 @@ import appeng.tile.crafting.TileCraftingTile; import appeng.util.Platform; import appeng.util.item.AEItemStack; + public class CraftingCPUCluster implements IAECluster, ICraftingCPU { - static class TaskProgress - { - - long value; - - } - + public final WorldCoord min; + public final WorldCoord max; + final int[] usedOps = new int[3]; + final Map tasks = new HashMap(); + // INSTANCE sate + final private LinkedList tiles = new LinkedList(); + final private LinkedList storage = new LinkedList(); + final private LinkedList status = new LinkedList(); + private final HashMap, Object> listeners = new HashMap, Object>(); + public ICraftingLink myLastLink; + public String myName = ""; + public boolean isDestroyed = false; /** * crafting job info */ MECraftingInventory inventory = new MECraftingInventory(); IAEItemStack finalOutput; - boolean waiting = false; - private boolean isComplete = true; - final int[] usedOps = new int[3]; - - final Map tasks = new HashMap(); IItemList waitingFor = AEApi.instance().storage().createItemList(); - - // INSTANCE sate - final private LinkedList tiles = new LinkedList(); - final private LinkedList storage = new LinkedList(); - final private LinkedList status = new LinkedList(); - long availableStorage = 0; - public ICraftingLink myLastLink; - MachineSource machineSrc = null; - public String myName = ""; - int accelerator = 0; - public final WorldCoord min; - public final WorldCoord max; - public boolean isDestroyed = false; + private boolean isComplete = true; + private int remainingOperations; + private boolean somethingChanged; - private final HashMap, Object> listeners = new HashMap, Object>(); - - protected Iterator, Object>> getListeners() + public CraftingCPUCluster( WorldCoord _min, WorldCoord _max ) { - return this.listeners.entrySet().iterator(); - } - - protected void postChange(IAEItemStack diff, BaseActionSource src) - { - Iterator, Object>> i = this.getListeners(); - - ImmutableList single = null; - - // protect integrity - if ( i.hasNext() ) - single = ImmutableList.of( diff.copy() ); - - while (i.hasNext()) - { - Entry, Object> o = i.next(); - IMEMonitorHandlerReceiver receiver = o.getKey(); - if ( receiver.isValid( o.getValue() ) ) - receiver.postChange( null, single, src ); - else - i.remove(); - } + this.min = _min; + this.max = _max; } /** * add a new Listener to the monitor, be sure to properly remove yourself when your done. */ @Override - public void addListener(IMEMonitorHandlerReceiver l, Object verificationToken) + public void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ) { this.listeners.put( l, verificationToken ); } @@ -159,94 +128,39 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU * remove a Listener to the monitor. */ @Override - public void removeListener(IMEMonitorHandlerReceiver l) + public void removeListener( IMEMonitorHandlerReceiver l ) { this.listeners.remove( l ); } - public void getListOfItem(IItemList list, CraftingItemList whichList) - { - switch (whichList) - { - case ACTIVE: - for (IAEItemStack ais : this.waitingFor) - list.add( ais ); - break; - case PENDING: - for (Entry t : this.tasks.entrySet()) - { - for (IAEItemStack ais : t.getKey().getCondensedOutputs()) - { - ais = ais.copy(); - ais.setStackSize( ais.getStackSize() * t.getValue().value ); - list.add( ais ); - } - } - break; - case STORAGE: - this.inventory.getAvailableItems( list ); - break; - default: - case ALL: - this.inventory.getAvailableItems( list ); - - for (IAEItemStack ais : this.waitingFor) - list.add( ais ); - - for (Entry t : this.tasks.entrySet()) - { - for (IAEItemStack ais : t.getKey().getCondensedOutputs()) - { - ais = ais.copy(); - ais.setStackSize( ais.getStackSize() * t.getValue().value ); - list.add( ais ); - } - } - break; - - } - } - - @Override - public Iterator getTiles() - { - return (Iterator) this.tiles.iterator(); - } - public IMEInventory getInventory() { return this.inventory; } - public CraftingCPUCluster(WorldCoord _min, WorldCoord _max) - { - this.min = _min; - this.max = _max; - } - @Override - public void updateStatus(boolean updateGrid) + public void updateStatus( boolean updateGrid ) { - for (TileCraftingTile r : this.tiles) + for( TileCraftingTile r : this.tiles ) r.updateMeta( true ); } @Override public void destroy() { - if ( this.isDestroyed ) + if( this.isDestroyed ) return; this.isDestroyed = true; boolean posted = false; - for (TileCraftingTile r : this.tiles) + for( TileCraftingTile r : this.tiles ) { IGridNode n = r.getActionableNode(); - if ( n != null && !posted ) + if( n != null && !posted ) { IGrid g = n.getGrid(); - if ( g != null ) + if( g != null ) { g.postEvent( new MENetworkCraftingCpuChange( n ) ); posted = true; @@ -258,84 +172,57 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU } @Override - public long getAvailableStorage() + public Iterator getTiles() { - return this.availableStorage; + return (Iterator) this.tiles.iterator(); } - @Override - public int getCoProcessors() + public void addTile( TileCraftingTile te ) { - return this.accelerator; - } - - public void addTile(TileCraftingTile te) - { - if ( this.machineSrc == null || te.isCoreBlock ) + if( this.machineSrc == null || te.isCoreBlock ) this.machineSrc = new MachineSource( te ); te.isCoreBlock = false; te.markDirty(); this.tiles.push( te ); - if ( te.isStorage() ) + if( te.isStorage() ) { this.availableStorage += te.getStorageBytes(); this.storage.add( te ); } - else if ( te.isStatus() ) + else if( te.isStatus() ) this.status.add( (TileCraftingMonitorTile) te ); - else if ( te.isAccelerator() ) + else if( te.isAccelerator() ) this.accelerator++; } - public boolean canAccept(IAEStack input) + public boolean canAccept( IAEStack input ) { - if ( input instanceof IAEItemStack ) + if( input instanceof IAEItemStack ) { IAEItemStack is = this.waitingFor.findPrecise( (IAEItemStack) input ); - if ( is != null && is.getStackSize() > 0 ) + if( is != null && is.getStackSize() > 0 ) return true; } return false; } - public void postCraftingStatusChange(IAEItemStack diff) + public IAEStack injectItems( IAEStack input, Actionable type, BaseActionSource src ) { - if ( this.getGrid() == null ) - return; - - CraftingGridCache sg = this.getGrid().getCache( ICraftingGrid.class ); - - if ( sg.interestManager.containsKey( diff ) ) - { - Collection list = sg.interestManager.get( diff ); - - if ( !list.isEmpty() ) - { - for (CraftingWatcher iw : list) - - iw.getHost().onRequestChange( sg, diff ); - } - } - - } - - public IAEStack injectItems(IAEStack input, Actionable type, BaseActionSource src) - { - if ( input instanceof IAEItemStack && type == Actionable.SIMULATE )// causes crafting to lock up? + if( input instanceof IAEItemStack && type == Actionable.SIMULATE )// causes crafting to lock up? { IAEItemStack what = (IAEItemStack) input.copy(); IAEItemStack is = this.waitingFor.findPrecise( what ); - if ( is != null && is.getStackSize() > 0 ) + if( is != null && is.getStackSize() > 0 ) { - if ( is.getStackSize() >= what.getStackSize() ) + if( is.getStackSize() >= what.getStackSize() ) { - if ( this.finalOutput.equals( what ) ) + if( this.finalOutput.equals( what ) ) { - if ( this.myLastLink != null ) - return ((CraftingLink) this.myLastLink).injectItems( what.copy(), type ); + if( this.myLastLink != null ) + return ( (CraftingLink) this.myLastLink ).injectItems( what.copy(), type ); return what; // ignore it. } @@ -349,11 +236,11 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU IAEItemStack used = what.copy(); used.setStackSize( is.getStackSize() ); - if ( this.finalOutput.equals( what ) ) + if( this.finalOutput.equals( what ) ) { - if ( this.myLastLink != null ) + if( this.myLastLink != null ) { - leftOver.add( ((CraftingLink) this.myLastLink).injectItems( used.copy(), type ) ); + leftOver.add( ( (CraftingLink) this.myLastLink ).injectItems( used.copy(), type ) ); return leftOver; } @@ -363,32 +250,32 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU return leftOver; } } - else if ( input instanceof IAEItemStack && type == Actionable.MODULATE ) + else if( input instanceof IAEItemStack && type == Actionable.MODULATE ) { IAEItemStack what = (IAEItemStack) input; IAEItemStack is = this.waitingFor.findPrecise( what ); - if ( is != null && is.getStackSize() > 0 ) + if( is != null && is.getStackSize() > 0 ) { this.waiting = false; this.postChange( (IAEItemStack) input, src ); - if ( is.getStackSize() >= input.getStackSize() ) + if( is.getStackSize() >= input.getStackSize() ) { is.decStackSize( input.getStackSize() ); this.markDirty(); this.postCraftingStatusChange( is ); - if ( this.finalOutput.equals( input ) ) + if( this.finalOutput.equals( input ) ) { this.finalOutput.decStackSize( input.getStackSize() ); - if ( this.finalOutput.getStackSize() <= 0 ) + if( this.finalOutput.getStackSize() <= 0 ) this.completeJob(); this.updateCPU(); - if ( this.myLastLink != null ) - return ((CraftingLink) this.myLastLink).injectItems( (IAEItemStack) input, type ); + if( this.myLastLink != null ) + return ( (CraftingLink) this.myLastLink ).injectItems( (IAEItemStack) input, type ); return input; // ignore it. } @@ -403,22 +290,22 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU is.setStackSize( 0 ); - if ( this.finalOutput.equals( insert ) ) + if( this.finalOutput.equals( insert ) ) { this.finalOutput.decStackSize( insert.getStackSize() ); - if ( this.finalOutput.getStackSize() <= 0 ) + if( this.finalOutput.getStackSize() <= 0 ) this.completeJob(); this.updateCPU(); - if ( this.myLastLink != null ) + if( this.myLastLink != null ) { - what.add( ((CraftingLink) this.myLastLink).injectItems( insert.copy(), type ) ); + what.add( ( (CraftingLink) this.myLastLink ).injectItems( insert.copy(), type ) ); return what; } - if ( this.myLastLink != null ) - return ((CraftingLink) this.myLastLink).injectItems( (IAEItemStack) input, type ); + if( this.myLastLink != null ) + return ( (CraftingLink) this.myLastLink ).injectItems( (IAEItemStack) input, type ); return input; // ignore it. } @@ -433,26 +320,91 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU return input; } + protected void postChange( IAEItemStack diff, BaseActionSource src ) + { + Iterator, Object>> i = this.getListeners(); + + ImmutableList single = null; + + // protect integrity + if( i.hasNext() ) + single = ImmutableList.of( diff.copy() ); + + while( i.hasNext() ) + { + Entry, Object> o = i.next(); + IMEMonitorHandlerReceiver receiver = o.getKey(); + if( receiver.isValid( o.getValue() ) ) + receiver.postChange( null, single, src ); + else + i.remove(); + } + } + + private void markDirty() + { + this.getCore().markDirty(); + } + + public void postCraftingStatusChange( IAEItemStack diff ) + { + if( this.getGrid() == null ) + return; + + CraftingGridCache sg = this.getGrid().getCache( ICraftingGrid.class ); + + if( sg.interestManager.containsKey( diff ) ) + { + Collection list = sg.interestManager.get( diff ); + + if( !list.isEmpty() ) + { + for( CraftingWatcher iw : list ) + + iw.getHost().onRequestChange( sg, diff ); + } + } + } + + private void completeJob() + { + if( this.myLastLink != null ) + ( (CraftingLink) this.myLastLink ).markDone(); + + AELog.crafting( "marking job as complete" ); + this.isComplete = true; + } + private void updateCPU() { IAEItemStack send = this.finalOutput; - if ( this.finalOutput != null && this.finalOutput.getStackSize() <= 0 ) + if( this.finalOutput != null && this.finalOutput.getStackSize() <= 0 ) send = null; - for (TileCraftingMonitorTile t : this.status) + for( TileCraftingMonitorTile t : this.status ) t.setJob( send ); } + protected Iterator, Object>> getListeners() + { + return this.listeners.entrySet().iterator(); + } + + private TileCraftingTile getCore() + { + return (TileCraftingTile) this.machineSrc.via; + } + public IGrid getGrid() { - for (TileCraftingTile r : this.tiles) + for( TileCraftingTile r : this.tiles ) { IGridNode gn = r.getActionableNode(); - if ( gn != null ) + if( gn != null ) { IGrid g = gn.getGrid(); - if ( g != null ) + if( g != null ) return r.getActionableNode().getGrid(); } } @@ -460,44 +412,35 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU return null; } - private void completeJob() + private boolean canCraft( ICraftingPatternDetails details, IAEItemStack[] condensedInputs ) { - if ( this.myLastLink != null ) - ((CraftingLink) this.myLastLink).markDone(); - - AELog.crafting( "marking job as complete" ); - this.isComplete = true; - } - - private boolean canCraft(ICraftingPatternDetails details, IAEItemStack[] condensedInputs) - { - for (IAEItemStack g : condensedInputs) + for( IAEItemStack g : condensedInputs ) { - if ( details.isCraftable() ) + if( details.isCraftable() ) { boolean found = false; - for (IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL )) + for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL ) ) { fuzz = fuzz.copy(); fuzz.setStackSize( g.getStackSize() ); IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE, this.machineSrc ); ItemStack is = ais == null ? null : ais.getItemStack(); - if ( is != null && is.stackSize == g.getStackSize() ) + if( is != null && is.stackSize == g.getStackSize() ) { found = true; break; } - else if ( is != null ) + else if( is != null ) { g = g.copy(); g.decStackSize( is.stackSize ); } } - if ( !found ) + if( !found ) return false; } else @@ -505,7 +448,7 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU IAEItemStack ais = this.inventory.extractItems( g.copy(), Actionable.SIMULATE, this.machineSrc ); ItemStack is = ais == null ? null : ais.getItemStack(); - if ( is == null || is.stackSize < g.getStackSize() ) + if( is == null || is.stackSize < g.getStackSize() ) return false; } } @@ -515,12 +458,12 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU public void cancel() { - if ( this.myLastLink != null ) + if( this.myLastLink != null ) this.myLastLink.cancel(); IItemList list; this.getListOfItem( list = AEApi.instance().storage().createItemList(), CraftingItemList.ALL ); - for (IAEItemStack is : list) + for( IAEItemStack is : list ) this.postChange( is, this.machineSrc ); this.isComplete = true; @@ -531,7 +474,7 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU this.waitingFor.resetStatus(); - for (IAEItemStack is : items) + for( IAEItemStack is : items ) this.postCraftingStatusChange( is ); this.finalOutput = null; @@ -540,23 +483,23 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU this.storeItems(); // marks dirty } - public void updateCraftingLogic(IGrid grid, IEnergyGrid eg, CraftingGridCache cc) + public void updateCraftingLogic( IGrid grid, IEnergyGrid eg, CraftingGridCache cc ) { - if ( !this.getCore().isActive() ) + if( !this.getCore().isActive() ) return; - if ( this.myLastLink != null ) + if( this.myLastLink != null ) { - if ( this.myLastLink.isCanceled() ) + if( this.myLastLink.isCanceled() ) { this.myLastLink = null; this.cancel(); } } - if ( this.isComplete ) + if( this.isComplete ) { - if ( this.inventory.getItemList().isEmpty() ) + if( this.inventory.getItemList().isEmpty() ) return; this.storeItems(); @@ -564,95 +507,92 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU } this.waiting = false; - if ( this.waiting || this.tasks.isEmpty() ) // nothing to do here... + if( this.waiting || this.tasks.isEmpty() ) // nothing to do here... return; - this.remainingOperations = this.accelerator + 1 - (this.usedOps[0] + this.usedOps[1] + this.usedOps[2]); + this.remainingOperations = this.accelerator + 1 - ( this.usedOps[0] + this.usedOps[1] + this.usedOps[2] ); int started = this.remainingOperations; - if ( this.remainingOperations > 0 ) + if( this.remainingOperations > 0 ) { do { this.somethingChanged = false; this.executeCrafting( eg, cc ); } - while (this.somethingChanged && this.remainingOperations > 0); + while( this.somethingChanged && this.remainingOperations > 0 ); } this.usedOps[2] = this.usedOps[1]; this.usedOps[1] = this.usedOps[0]; this.usedOps[0] = started - this.remainingOperations; - if ( this.remainingOperations > 0 && !this.somethingChanged ) + if( this.remainingOperations > 0 && !this.somethingChanged ) this.waiting = true; } - private int remainingOperations; - private boolean somethingChanged; - - private void executeCrafting(IEnergyGrid eg, CraftingGridCache cc) + private void executeCrafting( IEnergyGrid eg, CraftingGridCache cc ) { Iterator> i = this.tasks.entrySet().iterator(); - while (i.hasNext()) + while( i.hasNext() ) { Entry e = i.next(); - if ( e.getValue().value <= 0 ) + if( e.getValue().value <= 0 ) { i.remove(); continue; } ICraftingPatternDetails details = e.getKey(); - if ( this.canCraft( details, details.getCondensedInputs() ) ) + if( this.canCraft( details, details.getCondensedInputs() ) ) { InventoryCrafting ic = null; - for (ICraftingMedium m : cc.getMediums( e.getKey() )) + for( ICraftingMedium m : cc.getMediums( e.getKey() ) ) { - if ( e.getValue().value <= 0 ) + if( e.getValue().value <= 0 ) continue; - if ( !m.isBusy() ) + if( !m.isBusy() ) { - if ( ic == null ) + if( ic == null ) { IAEItemStack[] input = details.getInputs(); double sum = 0; - for (IAEItemStack anInput : input) + for( IAEItemStack anInput : input ) { - if ( anInput != null ) + if( anInput != null ) { sum += anInput.getStackSize(); } } // power... - if ( eg.extractAEPower( sum, Actionable.MODULATE, PowerMultiplier.CONFIG ) < sum - 0.01 ) + if( eg.extractAEPower( sum, Actionable.MODULATE, PowerMultiplier.CONFIG ) < sum - 0.01 ) continue; ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); boolean found = false; - for (int x = 0; x < input.length; x++) + for( int x = 0; x < input.length; x++ ) { - if ( input[x] != null ) + if( input[x] != null ) { found = false; - if ( details.isCraftable() ) + if( details.isCraftable() ) { - for (IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( input[x], FuzzyMode.IGNORE_ALL )) + for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( input[x], FuzzyMode.IGNORE_ALL ) ) { fuzz = fuzz.copy(); fuzz.setStackSize( input[x].getStackSize() ); - if ( details.isValidItemForSlot( x, fuzz.getItemStack(), this.getWorld() ) ) + if( details.isValidItemForSlot( x, fuzz.getItemStack(), this.getWorld() ) ) { IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.MODULATE, this.machineSrc ); ItemStack is = ais == null ? null : ais.getItemStack(); - if ( is != null ) + if( is != null ) { this.postChange( AEItemStack.create( is ), this.machineSrc ); ic.setInventorySlotContents( x, is ); @@ -667,11 +607,11 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU IAEItemStack ais = this.inventory.extractItems( input[x].copy(), Actionable.MODULATE, this.machineSrc ); ItemStack is = ais == null ? null : ais.getItemStack(); - if ( is != null ) + if( is != null ) { this.postChange( input[x], this.machineSrc ); ic.setInventorySlotContents( x, is ); - if ( is.stackSize == input[x].getStackSize() ) + if( is.stackSize == input[x].getStackSize() ) { found = true; continue; @@ -679,19 +619,18 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU } } - if ( !found ) + if( !found ) break; } - } - if ( !found ) + if( !found ) { // put stuff back.. - for (int x = 0; x < ic.getSizeInventory(); x++) + for( int x = 0; x < ic.getSizeInventory(); x++ ) { ItemStack is = ic.getStackInSlot( x ); - if ( is != null ) + if( is != null ) this.inventory.injectItems( AEItemStack.create( is ), Actionable.MODULATE, this.machineSrc ); } ic = null; @@ -699,27 +638,26 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU } } - if ( m.pushPattern( details, ic ) ) + if( m.pushPattern( details, ic ) ) { this.somethingChanged = true; this.remainingOperations--; - for (IAEItemStack out : details.getCondensedOutputs()) + for( IAEItemStack out : details.getCondensedOutputs() ) { this.postChange( out, this.machineSrc ); this.waitingFor.add( out.copy() ); this.postCraftingStatusChange( out.copy() ); } - if ( details.isCraftable() ) + if( details.isCraftable() ) { - FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.getWorld() ), - details.getOutput( ic, this.getWorld() ), ic ); + FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.getWorld() ), details.getOutput( ic, this.getWorld() ), ic ); - for (int x = 0; x < ic.getSizeInventory(); x++) + for( int x = 0; x < ic.getSizeInventory(); x++ ) { ItemStack output = Platform.getContainerItem( ic.getStackInSlot( x ) ); - if ( output != null ) + if( output != null ) { IAEItemStack cItem = AEItemStack.create( output ); this.postChange( cItem, this.machineSrc ); @@ -733,22 +671,22 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU this.markDirty(); e.getValue().value--; - if ( e.getValue().value <= 0 ) + if( e.getValue().value <= 0 ) continue; - if ( this.remainingOperations == 0 ) + if( this.remainingOperations == 0 ) return; } } } - if ( ic != null ) + if( ic != null ) { // put stuff back.. - for (int x = 0; x < ic.getSizeInventory(); x++) + for( int x = 0; x < ic.getSizeInventory(); x++ ) { ItemStack is = ic.getStackInSlot( x ); - if ( is != null ) + if( is != null ) { this.inventory.injectItems( AEItemStack.create( is ), Actionable.MODULATE, this.machineSrc ); } @@ -761,46 +699,41 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU private void storeItems() { IGrid g = this.getGrid(); - if ( g == null ) + if( g == null ) return; IStorageGrid sg = g.getCache( IStorageGrid.class ); IMEInventory ii = sg.getItemInventory(); - for (IAEItemStack is : this.inventory.getItemList()) + for( IAEItemStack is : this.inventory.getItemList() ) { is = this.inventory.extractItems( is.copy(), Actionable.MODULATE, this.machineSrc ); - if ( is != null ) + if( is != null ) { this.postChange( is, this.machineSrc ); is = ii.injectItems( is, Actionable.MODULATE, this.machineSrc ); } - if ( is != null ) + if( is != null ) this.inventory.injectItems( is, Actionable.MODULATE, this.machineSrc ); } - if ( this.inventory.getItemList().isEmpty() ) + if( this.inventory.getItemList().isEmpty() ) this.inventory = new MECraftingInventory(); this.markDirty(); } - private World getWorld() + public ICraftingLink submitJob( IGrid g, ICraftingJob job, BaseActionSource src, ICraftingRequester requestingMachine ) { - return this.getCore().getWorldObj(); - } - - public ICraftingLink submitJob(IGrid g, ICraftingJob job, BaseActionSource src, ICraftingRequester requestingMachine) - { - if ( !this.tasks.isEmpty() || !this.waitingFor.isEmpty() ) + if( !this.tasks.isEmpty() || !this.waitingFor.isEmpty() ) return null; - if ( !(job instanceof CraftingJob) ) + if( !( job instanceof CraftingJob ) ) return null; - if ( this.isBusy() || !this.isActive() || this.availableStorage < job.getByteTotal() ) + if( this.isBusy() || !this.isActive() || this.availableStorage < job.getByteTotal() ) return null; IStorageGrid sg = g.getCache( IStorageGrid.class ); @@ -810,8 +743,8 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU try { this.waitingFor.resetStatus(); - ((CraftingJob) job).tree.setJob( ci, this, src ); - if ( ci.commit( src ) ) + ( (CraftingJob) job ).tree.setJob( ci, this, src ); + if( ci.commit( src ) ) { this.finalOutput = job.getOutput(); this.waiting = false; @@ -823,7 +756,7 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU this.myLastLink = new CraftingLink( this.generateLinkData( craftID, requestingMachine == null, false ), this ); - if ( requestingMachine == null ) + if( requestingMachine == null ) return this.myLastLink; ICraftingLink whatLink = new CraftingLink( this.generateLinkData( craftID, false, true ), requestingMachine ); @@ -834,7 +767,7 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU IItemList list; this.getListOfItem( list = AEApi.instance().storage().createItemList(), CraftingItemList.ALL ); - for (IAEItemStack ge : list) + for( IAEItemStack ge : list ) this.postChange( ge, this.machineSrc ); return whatLink; @@ -845,7 +778,7 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU this.inventory.getItemList().resetStatus(); } } - catch (CraftBranchFailure e) + catch( CraftBranchFailure e ) { this.tasks.clear(); this.inventory.getItemList().resetStatus(); @@ -855,13 +788,54 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU return null; } - private void submitLink(ICraftingLink myLastLink2) + @Override + public boolean isBusy() { - if ( this.getGrid() != null ) + Iterator> i = this.tasks.entrySet().iterator(); + while( i.hasNext() ) { - CraftingGridCache cc = this.getGrid().getCache( ICraftingGrid.class ); - cc.addLink( (CraftingLink) myLastLink2 ); + if( i.next().getValue().value <= 0 ) + i.remove(); } + + return !this.tasks.isEmpty() || !this.waitingFor.isEmpty(); + } + + @Override + public BaseActionSource getActionSource() + { + return this.machineSrc; + } + + @Override + public long getAvailableStorage() + { + return this.availableStorage; + } + + @Override + public int getCoProcessors() + { + return this.accelerator; + } + + @Override + public String getName() + { + return this.myName; + } + + public boolean isActive() + { + TileCraftingTile core = this.getCore(); + if( core == null ) + return false; + + IGridNode node = core.getActionableNode(); + if( node == null ) + return false; + + return node.isActive(); } private String generateCraftingID() @@ -870,11 +844,10 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU int hash = System.identityHashCode( this ); int hmm = this.finalOutput == null ? 0 : this.finalOutput.hashCode(); - return Long.toString( now, Character.MAX_RADIX ) + '-' + Integer.toString( hash, Character.MAX_RADIX ) + '-' - + Integer.toString( hmm, Character.MAX_RADIX ); + return Long.toString( now, Character.MAX_RADIX ) + '-' + Integer.toString( hash, Character.MAX_RADIX ) + '-' + Integer.toString( hmm, Character.MAX_RADIX ); } - private NBTTagCompound generateLinkData(String craftingID, boolean standalone, boolean req) + private NBTTagCompound generateLinkData( String craftingID, boolean standalone, boolean req ) { NBTTagCompound tag = new NBTTagCompound(); @@ -887,82 +860,110 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU return tag; } - private void markDirty() + private void submitLink( ICraftingLink myLastLink2 ) { - this.getCore().markDirty(); + if( this.getGrid() != null ) + { + CraftingGridCache cc = this.getGrid().getCache( ICraftingGrid.class ); + cc.addLink( (CraftingLink) myLastLink2 ); + } } - private TileCraftingTile getCore() + public void getListOfItem( IItemList list, CraftingItemList whichList ) { - return (TileCraftingTile) this.machineSrc.via; + switch( whichList ) + { + case ACTIVE: + for( IAEItemStack ais : this.waitingFor ) + list.add( ais ); + break; + case PENDING: + for( Entry t : this.tasks.entrySet() ) + { + for( IAEItemStack ais : t.getKey().getCondensedOutputs() ) + { + ais = ais.copy(); + ais.setStackSize( ais.getStackSize() * t.getValue().value ); + list.add( ais ); + } + } + break; + case STORAGE: + this.inventory.getAvailableItems( list ); + break; + default: + case ALL: + this.inventory.getAvailableItems( list ); + + for( IAEItemStack ais : this.waitingFor ) + list.add( ais ); + + for( Entry t : this.tasks.entrySet() ) + { + for( IAEItemStack ais : t.getKey().getCondensedOutputs() ) + { + ais = ais.copy(); + ais.setStackSize( ais.getStackSize() * t.getValue().value ); + list.add( ais ); + } + } + break; + } } - public void addStorage(IAEItemStack extractItems) + public void addStorage( IAEItemStack extractItems ) { this.inventory.injectItems( extractItems, Actionable.MODULATE, null ); } - public void addEmitable(IAEItemStack i) + public void addEmitable( IAEItemStack i ) { this.waitingFor.add( i ); this.postCraftingStatusChange( i ); } - public void addCrafting(ICraftingPatternDetails details, long crafts) + public void addCrafting( ICraftingPatternDetails details, long crafts ) { TaskProgress i = this.tasks.get( details ); - if ( i == null ) + if( i == null ) this.tasks.put( details, i = new TaskProgress() ); i.value += crafts; } - @Override - public boolean isBusy() - { - Iterator> i = this.tasks.entrySet().iterator(); - while (i.hasNext()) - { - if ( i.next().getValue().value <= 0 ) - i.remove(); - } - - return !this.tasks.isEmpty() || !this.waitingFor.isEmpty(); - } - - public IAEItemStack getItemStack(IAEItemStack what, CraftingItemList storage2) + public IAEItemStack getItemStack( IAEItemStack what, CraftingItemList storage2 ) { IAEItemStack is = null; - switch (storage2) + switch( storage2 ) { - case STORAGE: - is = this.inventory.getItemList().findPrecise( what ); - break; - case ACTIVE: - is = this.waitingFor.findPrecise( what ); - break; - case PENDING: + case STORAGE: + is = this.inventory.getItemList().findPrecise( what ); + break; + case ACTIVE: + is = this.waitingFor.findPrecise( what ); + break; + case PENDING: - is = what.copy(); - is.setStackSize( 0 ); + is = what.copy(); + is.setStackSize( 0 ); - for (Entry t : this.tasks.entrySet()) - { - for (IAEItemStack ais : t.getKey().getCondensedOutputs()) + for( Entry t : this.tasks.entrySet() ) { - if ( ais.equals( is ) ) - is.setStackSize( is.getStackSize() + ais.getStackSize() * t.getValue().value ); + for( IAEItemStack ais : t.getKey().getCondensedOutputs() ) + { + if( ais.equals( is ) ) + is.setStackSize( is.getStackSize() + ais.getStackSize() * t.getValue().value ); + } } - } - break; - default: - case ALL: - throw new RuntimeException( "Invalid Operation" ); + break; + default: + case ALL: + throw new RuntimeException( "Invalid Operation" ); } - if ( is != null ) + if( is != null ) return is.copy(); is = what.copy(); @@ -970,53 +971,14 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU return is; } - public void readFromNBT(NBTTagCompound data) - { - this.finalOutput = AEItemStack.loadItemStackFromNBT( (NBTTagCompound) data.getTag( "finalOutput" ) ); - for (IAEItemStack ais : this.readList( (NBTTagList) data.getTag( "inventory" ) )) - this.inventory.injectItems( ais, Actionable.MODULATE, this.machineSrc ); - - this.waiting = data.getBoolean( "waiting" ); - this.isComplete = data.getBoolean( "isComplete" ); - - if ( data.hasKey( "link" ) ) - { - NBTTagCompound link = data.getCompoundTag( "link" ); - this.myLastLink = new CraftingLink( link, this ); - this.submitLink( this.myLastLink ); - } - - NBTTagList list = data.getTagList( "tasks", 10 ); - for (int x = 0; x < list.tagCount(); x++) - { - NBTTagCompound item = list.getCompoundTagAt( x ); - IAEItemStack pattern = AEItemStack.loadItemStackFromNBT( item ); - if ( pattern != null && pattern.getItem() instanceof ICraftingPatternItem ) - { - ICraftingPatternItem cpi = (ICraftingPatternItem) pattern.getItem(); - ICraftingPatternDetails details = cpi.getPatternForItem( pattern.getItemStack(), this.getWorld() ); - if ( details != null ) - { - TaskProgress tp = new TaskProgress(); - tp.value = item.getLong( "craftingProgress" ); - this.tasks.put( details, tp ); - } - } - } - - this.waitingFor = this.readList( (NBTTagList) data.getTag( "waitingFor" ) ); - for (IAEItemStack is : this.waitingFor) - this.postCraftingStatusChange( is.copy() ); - } - - public void writeToNBT(NBTTagCompound data) + public void writeToNBT( NBTTagCompound data ) { data.setTag( "finalOutput", this.writeItem( this.finalOutput ) ); data.setTag( "inventory", this.writeList( this.inventory.getItemList() ) ); data.setBoolean( "waiting", this.waiting ); data.setBoolean( "isComplete", this.isComplete ); - if ( this.myLastLink != null ) + if( this.myLastLink != null ) { NBTTagCompound link = new NBTTagCompound(); this.myLastLink.writeToNBT( link ); @@ -1024,7 +986,7 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU } NBTTagList list = new NBTTagList(); - for (Entry e : this.tasks.entrySet()) + for( Entry e : this.tasks.entrySet() ) { NBTTagCompound item = this.writeItem( AEItemStack.create( e.getKey().getPattern() ) ); item.setLong( "craftingProgress", e.getValue().value ); @@ -1035,49 +997,33 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU data.setTag( "waitingFor", this.writeList( this.waitingFor ) ); } - private IItemList readList(NBTTagList tag) - { - IItemList out = AEApi.instance().storage().createItemList(); - if ( tag == null ) - return out; - - for (int x = 0; x < tag.tagCount(); x++) - { - IAEItemStack ais = AEItemStack.loadItemStackFromNBT( tag.getCompoundTagAt( x ) ); - if ( ais != null ) - out.add( ais ); - } - - return out; - } - - private NBTTagList writeList(IItemList myList) - { - NBTTagList out = new NBTTagList(); - - for (IAEItemStack ais : myList) - out.appendTag( this.writeItem( ais ) ); - - return out; - } - - private NBTTagCompound writeItem(IAEItemStack finalOutput2) + private NBTTagCompound writeItem( IAEItemStack finalOutput2 ) { NBTTagCompound out = new NBTTagCompound(); - if ( finalOutput2 != null ) + if( finalOutput2 != null ) finalOutput2.writeToNBT( out ); return out; } + private NBTTagList writeList( IItemList myList ) + { + NBTTagList out = new NBTTagList(); + + for( IAEItemStack ais : myList ) + out.appendTag( this.writeItem( ais ) ); + + return out; + } + public void done() { TileCraftingTile core = this.getCore(); core.isCoreBlock = true; - if ( core.previousState != null ) + if( core.previousState != null ) { this.readFromNBT( core.previousState ); core.previousState = null; @@ -1087,49 +1033,83 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU this.updateName(); } - @Override - public BaseActionSource getActionSource() + public void readFromNBT( NBTTagCompound data ) { - return this.machineSrc; - } + this.finalOutput = AEItemStack.loadItemStackFromNBT( (NBTTagCompound) data.getTag( "finalOutput" ) ); + for( IAEItemStack ais : this.readList( (NBTTagList) data.getTag( "inventory" ) ) ) + this.inventory.injectItems( ais, Actionable.MODULATE, this.machineSrc ); - @Override - public String getName() - { - return this.myName; + this.waiting = data.getBoolean( "waiting" ); + this.isComplete = data.getBoolean( "isComplete" ); + + if( data.hasKey( "link" ) ) + { + NBTTagCompound link = data.getCompoundTag( "link" ); + this.myLastLink = new CraftingLink( link, this ); + this.submitLink( this.myLastLink ); + } + + NBTTagList list = data.getTagList( "tasks", 10 ); + for( int x = 0; x < list.tagCount(); x++ ) + { + NBTTagCompound item = list.getCompoundTagAt( x ); + IAEItemStack pattern = AEItemStack.loadItemStackFromNBT( item ); + if( pattern != null && pattern.getItem() instanceof ICraftingPatternItem ) + { + ICraftingPatternItem cpi = (ICraftingPatternItem) pattern.getItem(); + ICraftingPatternDetails details = cpi.getPatternForItem( pattern.getItemStack(), this.getWorld() ); + if( details != null ) + { + TaskProgress tp = new TaskProgress(); + tp.value = item.getLong( "craftingProgress" ); + this.tasks.put( details, tp ); + } + } + } + + this.waitingFor = this.readList( (NBTTagList) data.getTag( "waitingFor" ) ); + for( IAEItemStack is : this.waitingFor ) + this.postCraftingStatusChange( is.copy() ); } public void updateName() { this.myName = ""; - for (TileCraftingTile te : this.tiles) + for( TileCraftingTile te : this.tiles ) { - if ( te.hasCustomName() ) + if( te.hasCustomName() ) { - if ( this.myName.length() > 0 ) + if( this.myName.length() > 0 ) this.myName += ' ' + te.getCustomName(); else this.myName = te.getCustomName(); } - } } - public boolean isActive() + private IItemList readList( NBTTagList tag ) { - TileCraftingTile core = this.getCore(); - if ( core == null ) - return false; + IItemList out = AEApi.instance().storage().createItemList(); + if( tag == null ) + return out; - IGridNode node = core.getActionableNode(); - if ( node == null ) - return false; + for( int x = 0; x < tag.tagCount(); x++ ) + { + IAEItemStack ais = AEItemStack.loadItemStackFromNBT( tag.getCompoundTagAt( x ) ); + if( ais != null ) + out.add( ais ); + } - return node.isActive(); + return out; } - public boolean isMaking(IAEItemStack what) + private World getWorld() + { + return this.getCore().getWorldObj(); + } + + public boolean isMaking( IAEItemStack what ) { IAEItemStack wat = this.waitingFor.findPrecise( what ); return wat != null && wat.getStackSize() > 0; @@ -1138,8 +1118,13 @@ public class CraftingCPUCluster implements IAECluster, ICraftingCPU public void breakCluster() { TileCraftingTile t = this.getCore(); - if ( t != null ) + if( t != null ) t.breakCluster(); } + static class TaskProgress + { + + long value; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java b/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java index cffe3cbb8..fc270f21e 100644 --- a/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java @@ -18,6 +18,7 @@ package appeng.me.cluster.implementations; + import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; @@ -32,31 +33,27 @@ import appeng.me.cluster.IAEMultiBlock; import appeng.me.cluster.MBCalculator; import appeng.tile.qnb.TileQuantumBridge; + public class QuantumCalculator extends MBCalculator { final private TileQuantumBridge tqb; - public QuantumCalculator(IAEMultiBlock t) { + public QuantumCalculator( IAEMultiBlock t ) + { super( t ); this.tqb = (TileQuantumBridge) t; } @Override - public boolean isValidTile(TileEntity te) - { - return te instanceof TileQuantumBridge; - } - - @Override - public boolean checkMultiblockScale(WorldCoord min, WorldCoord max) + public boolean checkMultiblockScale( WorldCoord min, WorldCoord max ) { - if ( (max.x - min.x + 1) * (max.y - min.y + 1) * (max.z - min.z + 1) == 9 ) + if( ( max.x - min.x + 1 ) * ( max.y - min.y + 1 ) * ( max.z - min.z + 1 ) == 9 ) { - int ones = ((max.x - min.x) == 0 ? 1 : 0) + ((max.y - min.y) == 0 ? 1 : 0) + ((max.z - min.z) == 0 ? 1 : 0); + int ones = ( ( max.x - min.x ) == 0 ? 1 : 0 ) + ( ( max.y - min.y ) == 0 ? 1 : 0 ) + ( ( max.z - min.z ) == 0 ? 1 : 0 ); - int threes = ((max.x - min.x) == 2 ? 1 : 0) + ((max.y - min.y) == 2 ? 1 : 0) + ((max.z - min.z) == 2 ? 1 : 0); + int threes = ( ( max.x - min.x ) == 2 ? 1 : 0 ) + ( ( max.y - min.y ) == 2 ? 1 : 0 ) + ( ( max.z - min.z ) == 2 ? 1 : 0 ); return ones == 1 && threes == 2; } @@ -64,86 +61,40 @@ public class QuantumCalculator extends MBCalculator } @Override - public void updateTiles(IAECluster cl, World w, WorldCoord min, WorldCoord max) - { - byte num = 0; - byte ringNum = 0; - QuantumCluster c = (QuantumCluster) cl; - - for (int x = min.x; x <= max.x; x++) - { - for (int y = min.y; y <= max.y; y++) - { - for (int z = min.z; z <= max.z; z++) - { - TileQuantumBridge te = (TileQuantumBridge) w.getTileEntity( x, y, z ); - - byte flags; - - num++; - if ( num == 5 ) - { - flags = num; - c.setCenter( te ); - } - else - { - if ( num == 1 || num == 3 || num == 7 || num == 9 ) - flags = (byte) (this.tqb.corner | num); - else - flags = num; - c.Ring[ringNum] = te; - ringNum++; - } - - te.updateStatus( c, flags, true ); - } - } - } - - } - - @Override - public IAECluster createCluster(World w, WorldCoord min, WorldCoord max) + public IAECluster createCluster( World w, WorldCoord min, WorldCoord max ) { return new QuantumCluster( min, max ); } @Override - public void disconnect() - { - this.tqb.disconnect(true); - } - - @Override - public boolean verifyInternalStructure(World w, WorldCoord min, WorldCoord max) + public boolean verifyInternalStructure( World w, WorldCoord min, WorldCoord max ) { byte num = 0; - for (int x = min.x; x <= max.x; x++) + for( int x = min.x; x <= max.x; x++ ) { - for (int y = min.y; y <= max.y; y++) + for( int y = min.y; y <= max.y; y++ ) { - for (int z = min.z; z <= max.z; z++) + for( int z = min.z; z <= max.z; z++ ) { IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); - if ( !te.isValid() ) + if( !te.isValid() ) return false; num++; final IBlocks blocks = AEApi.instance().definitions().blocks(); - if ( num == 5 ) + if( num == 5 ) { - if ( !this.isBlockAtLocation( w, x, y, z, blocks.quantumLink() ) ) + if( !this.isBlockAtLocation( w, x, y, z, blocks.quantumLink() ) ) { return false; } } else { - if ( !this.isBlockAtLocation( w, x, y, z, blocks.quantumRing() ) ) + if( !this.isBlockAtLocation( w, x, y, z, blocks.quantumRing() ) ) { return false; } @@ -154,9 +105,60 @@ public class QuantumCalculator extends MBCalculator return true; } + @Override + public void disconnect() + { + this.tqb.disconnect( true ); + } + + @Override + public void updateTiles( IAECluster cl, World w, WorldCoord min, WorldCoord max ) + { + byte num = 0; + byte ringNum = 0; + QuantumCluster c = (QuantumCluster) cl; + + for( int x = min.x; x <= max.x; x++ ) + { + for( int y = min.y; y <= max.y; y++ ) + { + for( int z = min.z; z <= max.z; z++ ) + { + TileQuantumBridge te = (TileQuantumBridge) w.getTileEntity( x, y, z ); + + byte flags; + + num++; + if( num == 5 ) + { + flags = num; + c.setCenter( te ); + } + else + { + if( num == 1 || num == 3 || num == 7 || num == 9 ) + flags = (byte) ( this.tqb.corner | num ); + else + flags = num; + c.Ring[ringNum] = te; + ringNum++; + } + + te.updateStatus( c, flags, true ); + } + } + } + } + + @Override + public boolean isValidTile( TileEntity te ) + { + return te instanceof TileQuantumBridge; + } + private boolean isBlockAtLocation( IBlockAccess w, int x, int y, int z, IBlockDefinition def ) { - for ( Block block : def.maybeBlock().asSet() ) + for( Block block : def.maybeBlock().asSet() ) { return block == w.getBlock( x, y, z ); } diff --git a/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java b/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java index b30713ab0..b2c0766a1 100644 --- a/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java @@ -18,6 +18,7 @@ package appeng.me.cluster.implementations; + import java.util.Iterator; import net.minecraft.tileentity.TileEntity; @@ -43,6 +44,7 @@ import appeng.me.cluster.IAECluster; import appeng.tile.qnb.TileQuantumBridge; import appeng.util.iterators.ChainedIterator; + public class QuantumCluster implements ILocatable, IAECluster { @@ -50,61 +52,24 @@ public class QuantumCluster implements ILocatable, IAECluster final public WorldCoord max; public boolean isDestroyed = false; public boolean updateStatus = true; - + public TileQuantumBridge[] Ring; boolean registered = false; + ConnectionWrapper connection; private long thisSide; private long otherSide; - - ConnectionWrapper connection; - - public TileQuantumBridge[] Ring; private TileQuantumBridge center; - @Override - public Iterator getTiles() + public QuantumCluster( WorldCoord _min, WorldCoord _max ) { - return new ChainedIterator( this.Ring[0], this.Ring[1], this.Ring[2], this.Ring[3], this.Ring[4], this.Ring[5], this.Ring[6], this.Ring[7], this.center ); - } - - public void setCenter(TileQuantumBridge c) - { - this.registered = true; - MinecraftForge.EVENT_BUS.register( this ); - this.center = c; - } - - public QuantumCluster(WorldCoord _min, WorldCoord _max) { this.min = _min; this.max = _max; this.Ring = new TileQuantumBridge[8]; } - public boolean canUseNode(long qe) - { - QuantumCluster qc = (QuantumCluster) AEApi.instance().registries().locatable().getLocatableBy( qe ); - if ( qc != null ) - { - World theWorld = qc.center.getWorldObj(); - if ( !qc.isDestroyed ) - { - Chunk c = theWorld.getChunkFromBlockCoords( qc.center.xCoord, qc.center.zCoord ); - if ( c.isChunkLoaded ) - { - int id = theWorld.provider.dimensionId; - World cur = DimensionManager.getWorld( id ); - - TileEntity te = theWorld.getTileEntity( qc.center.xCoord, qc.center.yCoord, qc.center.zCoord ); - return te != qc.center || theWorld != cur; - } - } - } - return true; - } - @SubscribeEvent - public void onUnload(WorldEvent.Unload e) + public void onUnload( WorldEvent.Unload e ) { - if ( this.center.getWorldObj() == e.world ) + if( this.center.getWorldObj() == e.world ) { this.updateStatus = false; this.destroy(); @@ -112,25 +77,25 @@ public class QuantumCluster implements ILocatable, IAECluster } @Override - public void updateStatus(boolean updateGrid) + public void updateStatus( boolean updateGrid ) { long qe; qe = this.center.getQEFrequency(); - if ( this.thisSide != qe && this.thisSide != -qe ) + if( this.thisSide != qe && this.thisSide != -qe ) { - if ( qe != 0 ) + if( qe != 0 ) { - if ( this.thisSide != 0 ) + if( this.thisSide != 0 ) MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - if ( this.canUseNode( -qe ) ) + if( this.canUseNode( -qe ) ) { this.otherSide = qe; this.thisSide = -qe; } - else if ( this.canUseNode( qe ) ) + else if( this.canUseNode( qe ) ) { this.thisSide = qe; this.otherSide = -qe; @@ -151,37 +116,37 @@ public class QuantumCluster implements ILocatable, IAECluster boolean shutdown = false; - if ( myOtherSide instanceof QuantumCluster ) + if( myOtherSide instanceof QuantumCluster ) { QuantumCluster sideA = this; QuantumCluster sideB = (QuantumCluster) myOtherSide; - if ( sideA.isActive() && sideB.isActive() ) + if( sideA.isActive() && sideB.isActive() ) { - if ( this.connection != null && this.connection.connection != null ) + if( this.connection != null && this.connection.connection != null ) { IGridNode a = this.connection.connection.a(); IGridNode b = this.connection.connection.b(); IGridNode sa = sideA.getNode(); IGridNode sb = sideB.getNode(); - if ( (a == sa || b == sa) && (a == sb || b == sb) ) + if( ( a == sa || b == sa ) && ( a == sb || b == sb ) ) return; } try { - if ( sideA.connection != null ) + if( sideA.connection != null ) { - if ( sideA.connection.connection != null ) + if( sideA.connection.connection != null ) { sideA.connection.connection.destroy(); sideA.connection = new ConnectionWrapper( null ); } } - if ( sideB.connection != null ) + if( sideB.connection != null ) { - if ( sideB.connection.connection != null ) + if( sideB.connection.connection != null ) { sideB.connection.connection.destroy(); sideB.connection = new ConnectionWrapper( null ); @@ -190,7 +155,7 @@ public class QuantumCluster implements ILocatable, IAECluster sideA.connection = sideB.connection = new ConnectionWrapper( AEApi.instance().createGridConnection( sideA.getNode(), sideB.getNode() ) ); } - catch (FailedConnection e) + catch( FailedConnection e ) { // :( } @@ -201,9 +166,9 @@ public class QuantumCluster implements ILocatable, IAECluster else shutdown = true; - if ( shutdown && this.connection != null ) + if( shutdown && this.connection != null ) { - if ( this.connection.connection != null ) + if( this.connection.connection != null ) { this.connection.connection.destroy(); this.connection.connection = null; @@ -212,20 +177,60 @@ public class QuantumCluster implements ILocatable, IAECluster } } + public boolean canUseNode( long qe ) + { + QuantumCluster qc = (QuantumCluster) AEApi.instance().registries().locatable().getLocatableBy( qe ); + if( qc != null ) + { + World theWorld = qc.center.getWorldObj(); + if( !qc.isDestroyed ) + { + Chunk c = theWorld.getChunkFromBlockCoords( qc.center.xCoord, qc.center.zCoord ); + if( c.isChunkLoaded ) + { + int id = theWorld.provider.dimensionId; + World cur = DimensionManager.getWorld( id ); + + TileEntity te = theWorld.getTileEntity( qc.center.xCoord, qc.center.yCoord, qc.center.zCoord ); + return te != qc.center || theWorld != cur; + } + } + } + return true; + } + + private boolean isActive() + { + if( this.isDestroyed || !this.registered ) + return false; + + return this.center.isPowered() && this.hasQES(); + } + + private IGridNode getNode() + { + return this.center.getGridNode( ForgeDirection.UNKNOWN ); + } + + public boolean hasQES() + { + return this.thisSide != 0; + } + @Override public void destroy() { - if ( this.isDestroyed ) + if( this.isDestroyed ) return; this.isDestroyed = true; - if ( this.registered ) + if( this.registered ) { MinecraftForge.EVENT_BUS.unregister( this ); this.registered = false; } - if ( this.thisSide != 0 ) + if( this.thisSide != 0 ) { this.updateStatus( true ); MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); @@ -233,7 +238,7 @@ public class QuantumCluster implements ILocatable, IAECluster this.center.updateStatus( null, (byte) -1, this.updateStatus ); - for (TileQuantumBridge r : this.Ring) + for( TileQuantumBridge r : this.Ring ) { r.updateStatus( null, (byte) -1, this.updateStatus ); } @@ -242,7 +247,13 @@ public class QuantumCluster implements ILocatable, IAECluster this.Ring = new TileQuantumBridge[8]; } - public boolean isCorner(TileQuantumBridge tileQuantumBridge) + @Override + public Iterator getTiles() + { + return new ChainedIterator( this.Ring[0], this.Ring[1], this.Ring[2], this.Ring[3], this.Ring[4], this.Ring[5], this.Ring[6], this.Ring[7], this.center ); + } + + public boolean isCorner( TileQuantumBridge tileQuantumBridge ) { return this.Ring[0] == tileQuantumBridge || this.Ring[2] == tileQuantumBridge || this.Ring[4] == tileQuantumBridge || this.Ring[6] == tileQuantumBridge; } @@ -258,22 +269,10 @@ public class QuantumCluster implements ILocatable, IAECluster return this.center; } - public boolean hasQES() + public void setCenter( TileQuantumBridge c ) { - return this.thisSide != 0; + this.registered = true; + MinecraftForge.EVENT_BUS.register( this ); + this.center = c; } - - private IGridNode getNode() - { - return this.center.getGridNode( ForgeDirection.UNKNOWN ); - } - - private boolean isActive() - { - if ( this.isDestroyed || !this.registered ) - return false; - - return this.center.isPowered() && this.hasQES(); - } - } diff --git a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java index 4d537ac5d..9331de651 100644 --- a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java @@ -18,6 +18,7 @@ package appeng.me.cluster.implementations; + import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; @@ -28,75 +29,44 @@ import appeng.me.cluster.IAEMultiBlock; import appeng.me.cluster.MBCalculator; import appeng.tile.spatial.TileSpatialPylon; + public class SpatialPylonCalculator extends MBCalculator { private final TileSpatialPylon tqb; - public SpatialPylonCalculator(IAEMultiBlock t) { + public SpatialPylonCalculator( IAEMultiBlock t ) + { super( t ); this.tqb = (TileSpatialPylon) t; } @Override - public boolean isValidTile(TileEntity te) + public boolean checkMultiblockScale( WorldCoord min, WorldCoord max ) { - return te instanceof TileSpatialPylon; + return ( min.x == max.x && min.y == max.y && min.z != max.z ) || ( min.x == max.x && min.y != max.y && min.z == max.z ) || ( min.x != max.x && min.y == max.y && min.z == max.z ); } @Override - public boolean checkMultiblockScale(WorldCoord min, WorldCoord max) - { - return (min.x == max.x && min.y == max.y && min.z != max.z) || (min.x == max.x && min.y != max.y && min.z == max.z) || (min.x != max.x && min.y == max.y && min.z == max.z); - } - - @Override - public void updateTiles(IAECluster cl, World w, WorldCoord min, WorldCoord max) - { - SpatialPylonCluster c = (SpatialPylonCluster) cl; - - for (int x = min.x; x <= max.x; x++) - { - for (int y = min.y; y <= max.y; y++) - { - for (int z = min.z; z <= max.z; z++) - { - TileSpatialPylon te = (TileSpatialPylon) w.getTileEntity( x, y, z ); - te.updateStatus( c ); - c.line.add( (te) ); - } - } - } - - } - - @Override - public IAECluster createCluster(World w, WorldCoord min, WorldCoord max) + public IAECluster createCluster( World w, WorldCoord min, WorldCoord max ) { return new SpatialPylonCluster( new DimensionalCoord( w, min.x, min.y, min.z ), new DimensionalCoord( w, max.x, max.y, max.z ) ); } @Override - public void disconnect() - { - this.tqb.disconnect(true); - } - - @Override - public boolean verifyInternalStructure(World w, WorldCoord min, WorldCoord max) + public boolean verifyInternalStructure( World w, WorldCoord min, WorldCoord max ) { - for (int x = min.x; x <= max.x; x++) + for( int x = min.x; x <= max.x; x++ ) { - for (int y = min.y; y <= max.y; y++) + for( int y = min.y; y <= max.y; y++ ) { - for (int z = min.z; z <= max.z; z++) + for( int z = min.z; z <= max.z; z++ ) { IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); - if ( !te.isValid() ) + if( !te.isValid() ) return false; - } } } @@ -104,4 +74,34 @@ public class SpatialPylonCalculator extends MBCalculator return true; } + @Override + public void disconnect() + { + this.tqb.disconnect( true ); + } + + @Override + public void updateTiles( IAECluster cl, World w, WorldCoord min, WorldCoord max ) + { + SpatialPylonCluster c = (SpatialPylonCluster) cl; + + for( int x = min.x; x <= max.x; x++ ) + { + for( int y = min.y; y <= max.y; y++ ) + { + for( int z = min.z; z <= max.z; z++ ) + { + TileSpatialPylon te = (TileSpatialPylon) w.getTileEntity( x, y, z ); + te.updateStatus( c ); + c.line.add( ( te ) ); + } + } + } + } + + @Override + public boolean isValidTile( TileEntity te ) + { + return te instanceof TileSpatialPylon; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java index 38ee6265c..23dfa0f6b 100644 --- a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java @@ -18,6 +18,7 @@ package appeng.me.cluster.implementations; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -27,43 +28,39 @@ import appeng.api.util.DimensionalCoord; import appeng.me.cluster.IAECluster; import appeng.tile.spatial.TileSpatialPylon; + public class SpatialPylonCluster implements IAECluster { - public enum Axis - { - X, Y, Z, UNFORMED - } - final public DimensionalCoord min; final public DimensionalCoord max; + final List line = new ArrayList(); public boolean isDestroyed = false; public Axis currentAxis = Axis.UNFORMED; - - final List line = new ArrayList(); public boolean isValid; public boolean hasPower; public boolean hasChannel; - public SpatialPylonCluster(DimensionalCoord _min, DimensionalCoord _max) { + public SpatialPylonCluster( DimensionalCoord _min, DimensionalCoord _max ) + { this.min = _min.copy(); this.max = _max.copy(); - if ( this.min.x != this.max.x ) + if( this.min.x != this.max.x ) this.currentAxis = Axis.X; - else if ( this.min.y != this.max.y ) + else if( this.min.y != this.max.y ) this.currentAxis = Axis.Y; - else if ( this.min.z != this.max.z ) + else if( this.min.z != this.max.z ) this.currentAxis = Axis.Z; else this.currentAxis = Axis.UNFORMED; } @Override - public void updateStatus(boolean updateGrid) + public void updateStatus( boolean updateGrid ) { - for (TileSpatialPylon r : this.line) + for( TileSpatialPylon r : this.line ) { r.recalculateDisplay(); } @@ -73,20 +70,14 @@ public class SpatialPylonCluster implements IAECluster public void destroy() { - if ( this.isDestroyed ) + if( this.isDestroyed ) return; this.isDestroyed = true; - for (TileSpatialPylon r : this.line) + for( TileSpatialPylon r : this.line ) { r.updateStatus( null ); } - - } - - public int tileCount() - { - return this.line.size(); } @Override @@ -95,4 +86,13 @@ public class SpatialPylonCluster implements IAECluster return (Iterator) this.line.iterator(); } + public int tileCount() + { + return this.line.size(); + } + + public enum Axis + { + X, Y, Z, UNFORMED + } } diff --git a/src/main/java/appeng/me/energy/EnergyThreshold.java b/src/main/java/appeng/me/energy/EnergyThreshold.java index f5079df2a..5f89ac59b 100644 --- a/src/main/java/appeng/me/energy/EnergyThreshold.java +++ b/src/main/java/appeng/me/energy/EnergyThreshold.java @@ -18,9 +18,11 @@ package appeng.me.energy; + import appeng.api.networking.energy.IEnergyWatcher; import appeng.util.ItemSorters; + public class EnergyThreshold implements Comparable { @@ -28,14 +30,15 @@ public class EnergyThreshold implements Comparable public final IEnergyWatcher watcher; final int hash; - public EnergyThreshold(double lim, IEnergyWatcher wat) { + public EnergyThreshold( double lim, IEnergyWatcher wat ) + { this.Limit = lim; this.watcher = wat; - if ( this.watcher != null ) - this.hash = this.watcher.hashCode() ^ ((Double) lim).hashCode(); + if( this.watcher != null ) + this.hash = this.watcher.hashCode() ^ ( (Double) lim ).hashCode(); else - this.hash = ((Double) lim).hashCode(); + this.hash = ( (Double) lim ).hashCode(); } @Override @@ -45,9 +48,8 @@ public class EnergyThreshold implements Comparable } @Override - public int compareTo(EnergyThreshold o) + public int compareTo( EnergyThreshold o ) { return ItemSorters.compareDouble( this.Limit, o.Limit ); } - } diff --git a/src/main/java/appeng/me/energy/EnergyWatcher.java b/src/main/java/appeng/me/energy/EnergyWatcher.java index 5859d6e2f..c4ddc9aa0 100644 --- a/src/main/java/appeng/me/energy/EnergyWatcher.java +++ b/src/main/java/appeng/me/energy/EnergyWatcher.java @@ -18,6 +18,7 @@ package appeng.me.energy; + import java.util.Collection; import java.util.HashSet; import java.util.Iterator; @@ -26,12 +27,141 @@ import appeng.api.networking.energy.IEnergyWatcher; import appeng.api.networking.energy.IEnergyWatcherHost; import appeng.me.cache.EnergyGridCache; + /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ public class EnergyWatcher implements IEnergyWatcher { + final EnergyGridCache gsc; + final IEnergyWatcherHost myObject; + final HashSet myInterests = new HashSet(); + + public EnergyWatcher( EnergyGridCache cache, IEnergyWatcherHost host ) + { + this.gsc = cache; + this.myObject = host; + } + + public void post( EnergyGridCache energyGridCache ) + { + this.myObject.onThresholdPass( energyGridCache ); + } + + public IEnergyWatcherHost getHost() + { + return this.myObject; + } + + @Override + public int size() + { + return this.myInterests.size(); + } + + @Override + public boolean isEmpty() + { + return this.myInterests.isEmpty(); + } + + @Override + public boolean contains( Object o ) + { + return this.myInterests.contains( o ); + } + + @Override + public Iterator iterator() + { + return new EnergyWatcherIterator( this, this.myInterests.iterator() ); + } + + @Override + public Object[] toArray() + { + return this.myInterests.toArray(); + } + + @Override + public T[] toArray( T[] a ) + { + return this.myInterests.toArray( a ); + } + + @Override + public boolean add( Double e ) + { + if( this.myInterests.contains( e ) ) + return false; + + EnergyThreshold eh = new EnergyThreshold( e, this ); + return this.gsc.interests.add( eh ) && this.myInterests.add( eh ); + } + + @Override + public boolean remove( Object o ) + { + EnergyThreshold eh = new EnergyThreshold( (Double) o, this ); + return this.myInterests.remove( eh ) && this.gsc.interests.remove( eh ); + } + + @Override + public boolean containsAll( Collection c ) + { + return this.myInterests.containsAll( c ); + } + + @Override + public boolean addAll( Collection c ) + { + boolean didChange = false; + + for( Double o : c ) + didChange = this.add( o ) || didChange; + + return didChange; + } + + @Override + public boolean removeAll( Collection c ) + { + boolean didSomething = false; + for( Object o : c ) + didSomething = this.remove( o ) || didSomething; + return didSomething; + } + + @Override + public boolean retainAll( Collection c ) + { + boolean changed = false; + Iterator i = this.iterator(); + + while( i.hasNext() ) + { + if( !c.contains( i.next() ) ) + { + i.remove(); + changed = true; + } + } + + return changed; + } + + @Override + public void clear() + { + Iterator i = this.myInterests.iterator(); + while( i.hasNext() ) + { + this.gsc.interests.remove( i.next() ); + i.remove(); + } + } + class EnergyWatcherIterator implements Iterator { @@ -39,7 +169,8 @@ public class EnergyWatcher implements IEnergyWatcher final Iterator interestIterator; EnergyThreshold myLast; - public EnergyWatcherIterator(EnergyWatcher parent, Iterator i) { + public EnergyWatcherIterator( EnergyWatcher parent, Iterator i ) + { this.watcher = parent; this.interestIterator = i; } @@ -63,134 +194,5 @@ public class EnergyWatcher implements IEnergyWatcher EnergyWatcher.this.gsc.interests.remove( this.myLast ); this.interestIterator.remove(); } - } - - final EnergyGridCache gsc; - final IEnergyWatcherHost myObject; - final HashSet myInterests = new HashSet(); - - public void post(EnergyGridCache energyGridCache) - { - this.myObject.onThresholdPass( energyGridCache ); - } - - public EnergyWatcher(EnergyGridCache cache, IEnergyWatcherHost host) { - this.gsc = cache; - this.myObject = host; - } - - public IEnergyWatcherHost getHost() - { - return this.myObject; - } - - @Override - public boolean add(Double e) - { - if ( this.myInterests.contains( e ) ) - return false; - - EnergyThreshold eh = new EnergyThreshold( e, this ); - return this.gsc.interests.add( eh ) && this.myInterests.add( eh ); - } - - @Override - public boolean addAll(Collection c) - { - boolean didChange = false; - - for (Double o : c) - didChange = this.add( o ) || didChange; - - return didChange; - } - - @Override - public void clear() - { - Iterator i = this.myInterests.iterator(); - while (i.hasNext()) - { - this.gsc.interests.remove( i.next() ); - i.remove(); - } - } - - @Override - public boolean contains(Object o) - { - return this.myInterests.contains( o ); - } - - @Override - public boolean containsAll(Collection c) - { - return this.myInterests.containsAll( c ); - } - - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } - - @Override - public Iterator iterator() - { - return new EnergyWatcherIterator( this, this.myInterests.iterator() ); - } - - @Override - public boolean remove(Object o) - { - EnergyThreshold eh = new EnergyThreshold( (Double) o, this ); - return this.myInterests.remove( eh ) && this.gsc.interests.remove( eh ); - } - - @Override - public boolean removeAll(Collection c) - { - boolean didSomething = false; - for (Object o : c) - didSomething = this.remove( o ) || didSomething; - return didSomething; - } - - @Override - public boolean retainAll(Collection c) - { - boolean changed = false; - Iterator i = this.iterator(); - - while (i.hasNext()) - { - if ( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } - - return changed; - } - - @Override - public int size() - { - return this.myInterests.size(); - } - - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } - - @Override - public T[] toArray(T[] a) - { - return this.myInterests.toArray( a ); - } - } diff --git a/src/main/java/appeng/me/helpers/AENetworkProxy.java b/src/main/java/appeng/me/helpers/AENetworkProxy.java index 713aef12d..1a148cc15 100644 --- a/src/main/java/appeng/me/helpers/AENetworkProxy.java +++ b/src/main/java/appeng/me/helpers/AENetworkProxy.java @@ -18,6 +18,7 @@ package appeng.me.helpers; + import java.util.Collections; import java.util.EnumSet; @@ -51,40 +52,25 @@ import appeng.parts.networking.PartCable; import appeng.tile.AEBaseTile; import appeng.util.Platform; + public class AENetworkProxy implements IGridBlock { final private IGridProxyable gp; final private boolean worldNode; - + final private String nbtName; // name + public AEColor myColor = AEColor.Transparent; + NBTTagCompound data = null; // input private ItemStack myRepInstance; - private boolean isReady = false; private IGridNode node = null; - private EnumSet validSides; - public AEColor myColor = AEColor.Transparent; - private EnumSet flags = EnumSet.noneOf( GridFlags.class ); private double idleDraw = 1.0; - - final private String nbtName; // name - NBTTagCompound data = null; // input - private EntityPlayer owner; - @Override - public ItemStack getMachineRepresentation() + public AENetworkProxy( IGridProxyable te, String nbtName, ItemStack visual, boolean inWorld ) { - return this.myRepInstance; - } - - public void setVisualRepresentation(ItemStack is) - { - this.myRepInstance = is; - } - - public AENetworkProxy(IGridProxyable te, String nbtName, ItemStack visual, boolean inWorld) { this.gp = te; this.nbtName = nbtName; this.worldNode = inWorld; @@ -92,27 +78,201 @@ public class AENetworkProxy implements IGridBlock this.validSides = EnumSet.allOf( ForgeDirection.class ); } - public void writeToNBT(NBTTagCompound tag) + public void setVisualRepresentation( ItemStack is ) { - if ( this.node != null ) + this.myRepInstance = is; + } + + public void writeToNBT( NBTTagCompound tag ) + { + if( this.node != null ) this.node.saveToNBT( this.nbtName, tag ); } - public void readFromNBT(NBTTagCompound tag) + public void setValidSides( EnumSet validSides ) + { + this.validSides = validSides; + if( this.node != null ) + this.node.updateState(); + } + + public void validate() + { + if( this.gp instanceof AEBaseTile ) + TickHandler.INSTANCE.addInit( (AEBaseTile) this.gp ); + } + + public void onChunkUnload() + { + this.isReady = false; + this.invalidate(); + } + + public void invalidate() + { + this.isReady = false; + if( this.node != null ) + { + this.node.destroy(); + this.node = null; + } + } + + public void onReady() + { + this.isReady = true; + + // send orientation based directionality to the node. + if( this.gp instanceof IOrientable ) + { + IOrientable ori = (IOrientable) this.gp; + if( ori.canBeRotated() ) + ori.setOrientation( ori.getForward(), ori.getUp() ); + } + + this.getNode(); + } + + public IGridNode getNode() + { + if( this.node == null && Platform.isServer() && this.isReady ) + { + this.node = AEApi.instance().createGridNode( this ); + this.readFromNBT( this.data ); + this.node.updateState(); + } + + return this.node; + } + + public void readFromNBT( NBTTagCompound tag ) { this.data = tag; - if ( this.node != null && this.data != null ) + if( this.node != null && this.data != null ) { this.node.loadFromNBT( this.nbtName, this.data ); this.data = null; } - else if ( this.node != null && this.owner != null ) + else if( this.node != null && this.owner != null ) { this.node.setPlayerID( WorldSettings.getInstance().getPlayerID( this.owner.getGameProfile() ) ); this.owner = null; } } + public IPathingGrid getPath() throws GridAccessException + { + IGrid grid = this.getGrid(); + if( grid == null ) + throw new GridAccessException(); + IPathingGrid pg = grid.getCache( IPathingGrid.class ); + if( pg == null ) + throw new GridAccessException(); + return pg; + } + + /** + * short cut! + * + * @return grid of node + * + * @throws GridAccessException of node or grid is null + */ + public IGrid getGrid() throws GridAccessException + { + if( this.node == null ) + throw new GridAccessException(); + IGrid grid = this.node.getGrid(); + if( grid == null ) + throw new GridAccessException(); + return grid; + } + + public ITickManager getTick() throws GridAccessException + { + IGrid grid = this.getGrid(); + if( grid == null ) + throw new GridAccessException(); + ITickManager pg = grid.getCache( ITickManager.class ); + if( pg == null ) + throw new GridAccessException(); + return pg; + } + + public IStorageGrid getStorage() throws GridAccessException + { + IGrid grid = this.getGrid(); + if( grid == null ) + throw new GridAccessException(); + + IStorageGrid pg = grid.getCache( IStorageGrid.class ); + + if( pg == null ) + throw new GridAccessException(); + + return pg; + } + + public P2PCache getP2P() throws GridAccessException + { + IGrid grid = this.getGrid(); + if( grid == null ) + throw new GridAccessException(); + + P2PCache pg = grid.getCache( P2PCache.class ); + + if( pg == null ) + throw new GridAccessException(); + + return pg; + } + + public ISecurityGrid getSecurity() throws GridAccessException + { + IGrid grid = this.getGrid(); + if( grid == null ) + throw new GridAccessException(); + + ISecurityGrid sg = grid.getCache( ISecurityGrid.class ); + + if( sg == null ) + throw new GridAccessException(); + + return sg; + } + + public ICraftingGrid getCrafting() throws GridAccessException + { + IGrid grid = this.getGrid(); + if( grid == null ) + throw new GridAccessException(); + + ICraftingGrid sg = grid.getCache( ICraftingGrid.class ); + + if( sg == null ) + throw new GridAccessException(); + + return sg; + } + + @Override + public double getIdlePowerUsage() + { + return this.idleDraw; + } + + @Override + public EnumSet getFlags() + { + return this.flags; + } + + @Override + public boolean isWorldAccessible() + { + return this.worldNode; + } + @Override public DimensionalCoord getLocation() { @@ -126,14 +286,14 @@ public class AENetworkProxy implements IGridBlock } @Override - public void onGridNotification(GridNotification notification) + public void onGridNotification( GridNotification notification ) { - if ( this.gp instanceof PartCable ) - ((PartCable) this.gp).markForUpdate(); + if( this.gp instanceof PartCable ) + ( (PartCable) this.gp ).markForUpdate(); } @Override - public void setNetworkStatus(IGrid grid, int channelsInUse) + public void setNetworkStatus( IGrid grid, int channelsInUse ) { } @@ -144,186 +304,25 @@ public class AENetworkProxy implements IGridBlock return this.validSides; } - public void setValidSides(EnumSet validSides) - { - this.validSides = validSides; - if ( this.node != null ) - this.node.updateState(); - } - - public IGridNode getNode() - { - if ( this.node == null && Platform.isServer() && this.isReady ) - { - this.node = AEApi.instance().createGridNode( this ); - this.readFromNBT( this.data ); - this.node.updateState(); - } - - return this.node; - } - - public void validate() - { - if ( this.gp instanceof AEBaseTile ) - TickHandler.INSTANCE.addInit( (AEBaseTile) this.gp ); - } - - public void onChunkUnload() - { - this.isReady = false; - this.invalidate(); - } - - public void invalidate() - { - this.isReady = false; - if ( this.node != null ) - { - this.node.destroy(); - this.node = null; - } - } - - public void onReady() - { - this.isReady = true; - - // send orientation based directionality to the node. - if ( this.gp instanceof IOrientable ) - { - IOrientable ori = (IOrientable) this.gp; - if ( ori.canBeRotated() ) - ori.setOrientation( ori.getForward(), ori.getUp() ); - } - - this.getNode(); - } - @Override public IGridHost getMachine() { return this.gp; } - /** - * short cut! - * - * @return grid of node - * @throws GridAccessException of node or grid is null - */ - public IGrid getGrid() throws GridAccessException + @Override + public void gridChanged() { - if ( this.node == null ) - throw new GridAccessException(); - IGrid grid = this.node.getGrid(); - if ( grid == null ) - throw new GridAccessException(); - return grid; - } - - public IEnergyGrid getEnergy() throws GridAccessException - { - IGrid grid = this.getGrid(); - if ( grid == null ) - throw new GridAccessException(); - IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); - if ( eg == null ) - throw new GridAccessException(); - return eg; - } - - public IPathingGrid getPath() throws GridAccessException - { - IGrid grid = this.getGrid(); - if ( grid == null ) - throw new GridAccessException(); - IPathingGrid pg = grid.getCache( IPathingGrid.class ); - if ( pg == null ) - throw new GridAccessException(); - return pg; - } - - public ITickManager getTick() throws GridAccessException - { - IGrid grid = this.getGrid(); - if ( grid == null ) - throw new GridAccessException(); - ITickManager pg = grid.getCache( ITickManager.class ); - if ( pg == null ) - throw new GridAccessException(); - return pg; - } - - public IStorageGrid getStorage() throws GridAccessException - { - IGrid grid = this.getGrid(); - if ( grid == null ) - throw new GridAccessException(); - - IStorageGrid pg = grid.getCache( IStorageGrid.class ); - - if ( pg == null ) - throw new GridAccessException(); - - return pg; - } - - public P2PCache getP2P() throws GridAccessException - { - IGrid grid = this.getGrid(); - if ( grid == null ) - throw new GridAccessException(); - - P2PCache pg = grid.getCache( P2PCache.class ); - - if ( pg == null ) - throw new GridAccessException(); - - return pg; - } - - public ISecurityGrid getSecurity() throws GridAccessException - { - IGrid grid = this.getGrid(); - if ( grid == null ) - throw new GridAccessException(); - - ISecurityGrid sg = grid.getCache( ISecurityGrid.class ); - - if ( sg == null ) - throw new GridAccessException(); - - return sg; - } - - public ICraftingGrid getCrafting() throws GridAccessException - { - IGrid grid = this.getGrid(); - if ( grid == null ) - throw new GridAccessException(); - - ICraftingGrid sg = grid.getCache( ICraftingGrid.class ); - - if ( sg == null ) - throw new GridAccessException(); - - return sg; + this.gp.gridChanged(); } @Override - public boolean isWorldAccessible() + public ItemStack getMachineRepresentation() { - return this.worldNode; + return this.myRepInstance; } - @Override - public EnumSet getFlags() - { - return this.flags; - } - - public void setFlags(GridFlags... requireChannel) + public void setFlags( GridFlags... requireChannel ) { EnumSet flags = EnumSet.noneOf( GridFlags.class ); @@ -332,24 +331,18 @@ public class AENetworkProxy implements IGridBlock this.flags = flags; } - @Override - public double getIdlePowerUsage() - { - return this.idleDraw; - } - - public void setIdlePowerUsage(double idle) + public void setIdlePowerUsage( double idle ) { this.idleDraw = idle; - if ( this.node != null ) + if( this.node != null ) { try { IGrid g = this.getGrid(); g.postEvent( new MENetworkPowerIdleChange( this.node ) ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // not ready for this yet.. } @@ -363,7 +356,7 @@ public class AENetworkProxy implements IGridBlock public boolean isActive() { - if ( this.node == null ) + if( this.node == null ) return false; return this.node.isActive(); @@ -375,21 +368,25 @@ public class AENetworkProxy implements IGridBlock { return this.getEnergy().isNetworkPowered(); } - catch (GridAccessException e) + catch( GridAccessException e ) { return false; } } - @Override - public void gridChanged() + public IEnergyGrid getEnergy() throws GridAccessException { - this.gp.gridChanged(); + IGrid grid = this.getGrid(); + if( grid == null ) + throw new GridAccessException(); + IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); + if( eg == null ) + throw new GridAccessException(); + return eg; } - public void setOwner(EntityPlayer player) + public void setOwner( EntityPlayer player ) { this.owner = player; } - } diff --git a/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java b/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java index 427be56d1..b060a34ee 100644 --- a/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java +++ b/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java @@ -18,6 +18,7 @@ package appeng.me.helpers; + import java.util.Iterator; import net.minecraft.item.ItemStack; @@ -29,24 +30,26 @@ import appeng.me.cluster.IAEMultiBlock; import appeng.util.iterators.ChainedIterator; import appeng.util.iterators.ProxyNodeIterator; + public class AENetworkProxyMultiblock extends AENetworkProxy implements IGridMultiblock { - IAECluster getCluster() + public AENetworkProxyMultiblock( IGridProxyable te, String nbtName, ItemStack itemStack, boolean inWorld ) { - return ((IAEMultiBlock) this.getMachine()).getCluster(); - } - - public AENetworkProxyMultiblock(IGridProxyable te, String nbtName, ItemStack itemStack, boolean inWorld) { super( te, nbtName, itemStack, inWorld ); } @Override public Iterator getMultiblockNodes() { - if ( this.getCluster() == null ) + if( this.getCluster() == null ) return new ChainedIterator(); return new ProxyNodeIterator( this.getCluster().getTiles() ); } + + IAECluster getCluster() + { + return ( (IAEMultiBlock) this.getMachine() ).getCluster(); + } } diff --git a/src/main/java/appeng/me/helpers/ChannelPowerSrc.java b/src/main/java/appeng/me/helpers/ChannelPowerSrc.java index 2c83ea6b7..5c71414d4 100644 --- a/src/main/java/appeng/me/helpers/ChannelPowerSrc.java +++ b/src/main/java/appeng/me/helpers/ChannelPowerSrc.java @@ -18,28 +18,30 @@ package appeng.me.helpers; + import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergySource; + public class ChannelPowerSrc implements IEnergySource { final IGridNode node; final IEnergySource realSrc; - public ChannelPowerSrc(IGridNode networkNode, IEnergySource src) { + public ChannelPowerSrc( IGridNode networkNode, IEnergySource src ) + { this.node = networkNode; this.realSrc = src; } @Override - public double extractAEPower(double amt, Actionable mode, PowerMultiplier usePowerMultiplier) + public double extractAEPower( double amt, Actionable mode, PowerMultiplier usePowerMultiplier ) { - if ( this.node.isActive() ) + if( this.node.isActive() ) return this.realSrc.extractAEPower( amt, mode, usePowerMultiplier ); return 0.0; } - } diff --git a/src/main/java/appeng/me/helpers/GenericInterestManager.java b/src/main/java/appeng/me/helpers/GenericInterestManager.java index 44e33ee77..3ed709c9c 100644 --- a/src/main/java/appeng/me/helpers/GenericInterestManager.java +++ b/src/main/java/appeng/me/helpers/GenericInterestManager.java @@ -18,6 +18,7 @@ package appeng.me.helpers; + import java.util.Collection; import java.util.LinkedList; @@ -25,34 +26,22 @@ import com.google.common.collect.Multimap; import appeng.api.storage.data.IAEStack; + public class GenericInterestManager { - class SavedTransactions - { - - public final boolean put; - public final IAEStack stack; - public final T iw; - - public SavedTransactions(boolean putOperation, IAEStack myStack, T watcher) { - this.put = putOperation; - this.stack = myStack; - this.iw = watcher; - } - } - private final Multimap container; private LinkedList transactions = null; private int transDepth = 0; - public GenericInterestManager(Multimap interests) { + public GenericInterestManager( Multimap interests ) + { this.container = interests; } public void enableTransactions() { - if ( this.transDepth == 0 ) + if( this.transDepth == 0 ) this.transactions = new LinkedList(); this.transDepth++; @@ -62,14 +51,14 @@ public class GenericInterestManager { this.transDepth--; - if ( this.transDepth == 0 ) + if( this.transDepth == 0 ) { LinkedList myActions = this.transactions; this.transactions = null; - for (SavedTransactions t : myActions) + for( SavedTransactions t : myActions ) { - if ( t.put ) + if( t.put ) this.put( t.stack, t.iw ); else this.remove( t.stack, t.iw ); @@ -77,19 +66,9 @@ public class GenericInterestManager } } - public boolean containsKey(IAEStack stack) + public boolean put( IAEStack stack, T iw ) { - return this.container.containsKey( stack ); - } - - public Collection get(IAEStack stack) - { - return this.container.get( stack ); - } - - public boolean put(IAEStack stack, T iw) - { - if ( this.transactions != null ) + if( this.transactions != null ) { this.transactions.add( new SavedTransactions( true, stack, iw ) ); return true; @@ -98,9 +77,9 @@ public class GenericInterestManager return this.container.put( stack, iw ); } - public boolean remove(IAEStack stack, T iw) + public boolean remove( IAEStack stack, T iw ) { - if ( this.transactions != null ) + if( this.transactions != null ) { this.transactions.add( new SavedTransactions( true, stack, iw ) ); return true; @@ -109,4 +88,28 @@ public class GenericInterestManager return this.container.remove( stack, iw ); } + public boolean containsKey( IAEStack stack ) + { + return this.container.containsKey( stack ); + } + + public Collection get( IAEStack stack ) + { + return this.container.get( stack ); + } + + class SavedTransactions + { + + public final boolean put; + public final IAEStack stack; + public final T iw; + + public SavedTransactions( boolean putOperation, IAEStack myStack, T watcher ) + { + this.put = putOperation; + this.stack = myStack; + this.iw = watcher; + } + } } diff --git a/src/main/java/appeng/me/helpers/IGridProxyable.java b/src/main/java/appeng/me/helpers/IGridProxyable.java index 2a963882a..916a5659a 100644 --- a/src/main/java/appeng/me/helpers/IGridProxyable.java +++ b/src/main/java/appeng/me/helpers/IGridProxyable.java @@ -18,9 +18,11 @@ package appeng.me.helpers; + import appeng.api.networking.IGridHost; import appeng.api.util.DimensionalCoord; + public interface IGridProxyable extends IGridHost { diff --git a/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java b/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java index 42600dee9..828a0fa54 100644 --- a/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java +++ b/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java @@ -18,23 +18,26 @@ package appeng.me.pathfinding; + import appeng.api.networking.IGridConnection; import appeng.api.networking.IGridConnectionVisitor; import appeng.api.networking.IGridNode; import appeng.me.GridConnection; import appeng.me.GridNode; + public class AdHocChannelUpdater implements IGridConnectionVisitor { final private int usedChannels; - public AdHocChannelUpdater(int used) { + public AdHocChannelUpdater( int used ) + { this.usedChannels = used; } @Override - public boolean visitNode(IGridNode n) + public boolean visitNode( IGridNode n ) { GridNode gn = (GridNode) n; gn.setControllerRoute( null, true ); @@ -44,7 +47,7 @@ public class AdHocChannelUpdater implements IGridConnectionVisitor } @Override - public void visitConnection(IGridConnection gcc) + public void visitConnection( IGridConnection gcc ) { GridConnection gc = (GridConnection) gcc; gc.setControllerRoute( null, true ); diff --git a/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java b/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java index 7e944db89..e7bba5b16 100644 --- a/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java +++ b/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java @@ -18,17 +18,19 @@ package appeng.me.pathfinding; + import appeng.api.networking.IGridConnection; import appeng.api.networking.IGridConnectionVisitor; import appeng.api.networking.IGridNode; import appeng.me.GridConnection; import appeng.me.GridNode; + public class ControllerChannelUpdater implements IGridConnectionVisitor { @Override - public boolean visitNode(IGridNode n) + public boolean visitNode( IGridNode n ) { GridNode gn = (GridNode) n; gn.finalizeChannels(); @@ -36,7 +38,7 @@ public class ControllerChannelUpdater implements IGridConnectionVisitor } @Override - public void visitConnection(IGridConnection gcc) + public void visitConnection( IGridConnection gcc ) { GridConnection gc = (GridConnection) gcc; gc.finalizeChannels(); diff --git a/src/main/java/appeng/me/pathfinding/ControllerValidator.java b/src/main/java/appeng/me/pathfinding/ControllerValidator.java index a1f7a5e70..45ebc4268 100644 --- a/src/main/java/appeng/me/pathfinding/ControllerValidator.java +++ b/src/main/java/appeng/me/pathfinding/ControllerValidator.java @@ -18,26 +18,27 @@ package appeng.me.pathfinding; + import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; import appeng.tile.networking.TileController; + public class ControllerValidator implements IGridVisitor { + public boolean isValid = true; + public int found = 0; int minX; int minY; int minZ; - int maxX; int maxY; int maxZ; - public boolean isValid = true; - public int found = 0; - - public ControllerValidator(int x, int y, int z) { + public ControllerValidator( int x, int y, int z ) + { this.minX = x; this.minY = y; this.minZ = z; @@ -47,10 +48,10 @@ public class ControllerValidator implements IGridVisitor } @Override - public boolean visitNode(IGridNode n) + public boolean visitNode( IGridNode n ) { IGridHost host = n.getMachine(); - if ( this.isValid && host instanceof TileController ) + if( this.isValid && host instanceof TileController ) { TileController c = (TileController) host; @@ -61,7 +62,7 @@ public class ControllerValidator implements IGridVisitor this.minZ = Math.min( c.zCoord, this.minZ ); this.maxZ = Math.max( c.zCoord, this.maxZ ); - if ( this.maxX - this.minX < 7 && this.maxY - this.minY < 7 && this.maxZ - this.minZ < 7 ) + if( this.maxX - this.minX < 7 && this.maxY - this.minY < 7 && this.maxZ - this.minZ < 7 ) { this.found++; return true; diff --git a/src/main/java/appeng/me/pathfinding/IPathItem.java b/src/main/java/appeng/me/pathfinding/IPathItem.java index c7c022b42..bc9835a2c 100644 --- a/src/main/java/appeng/me/pathfinding/IPathItem.java +++ b/src/main/java/appeng/me/pathfinding/IPathItem.java @@ -18,17 +18,19 @@ package appeng.me.pathfinding; + import java.util.EnumSet; import appeng.api.networking.GridFlags; import appeng.api.util.IReadOnlyCollection; + public interface IPathItem { IPathItem getControllerRoute(); - void setControllerRoute(IPathItem fast, boolean zeroOut); + void setControllerRoute( IPathItem fast, boolean zeroOut ); /** * used to determine if the finder can continue. @@ -43,7 +45,7 @@ public interface IPathItem /** * add one to the channel count, this is mostly for cables. */ - void incrementChannelCount(int usedChannels); + void incrementChannelCount( int usedChannels ); /** * get the grid flags for this IPathItem. @@ -56,5 +58,4 @@ public interface IPathItem * channels are done, wrap it up. */ void finalizeChannels(); - } diff --git a/src/main/java/appeng/me/pathfinding/PathSegment.java b/src/main/java/appeng/me/pathfinding/PathSegment.java index 0b073d3cf..ceb0d113f 100644 --- a/src/main/java/appeng/me/pathfinding/PathSegment.java +++ b/src/main/java/appeng/me/pathfinding/PathSegment.java @@ -18,6 +18,7 @@ package appeng.me.pathfinding; + import java.util.EnumSet; import java.util.Iterator; import java.util.LinkedList; @@ -29,14 +30,17 @@ import appeng.api.networking.IGridMultiblock; import appeng.api.networking.IGridNode; import appeng.me.cache.PathGridCache; + public class PathSegment { - public boolean isDead; - final PathGridCache pgc; + final Set semiOpen; + final Set closed; + public boolean isDead; + List open; - public PathSegment(PathGridCache myPGC, List open, Set semiOpen, Set closed) + public PathSegment( PathGridCache myPGC, List open, Set semiOpen, Set closed ) { this.open = open; this.semiOpen = semiOpen; @@ -45,44 +49,40 @@ public class PathSegment this.isDead = false; } - List open; - final Set semiOpen; - final Set closed; - public boolean step() { List oldOpen = this.open; this.open = new LinkedList(); - for (IPathItem i : oldOpen) + for( IPathItem i : oldOpen ) { - for (IPathItem pi : i.getPossibleOptions()) + for( IPathItem pi : i.getPossibleOptions() ) { EnumSet flags = pi.getFlags(); - if ( !this.closed.contains( pi ) ) + if( !this.closed.contains( pi ) ) { pi.setControllerRoute( i, true ); - if ( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) + if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) { // close the semi open. - if ( !this.semiOpen.contains( pi ) ) + if( !this.semiOpen.contains( pi ) ) { boolean worked; - if ( flags.contains( GridFlags.COMPRESSED_CHANNEL ) ) + if( flags.contains( GridFlags.COMPRESSED_CHANNEL ) ) worked = this.useDenseChannel( pi ); else worked = this.useChannel( pi ); - if ( worked && flags.contains( GridFlags.MULTIBLOCK ) ) + if( worked && flags.contains( GridFlags.MULTIBLOCK ) ) { - Iterator oni = ((IGridMultiblock) ((IGridNode) pi).getGridBlock()).getMultiblockNodes(); - while (oni.hasNext()) + Iterator oni = ( (IGridMultiblock) ( (IGridNode) pi ).getGridBlock() ).getMultiblockNodes(); + while( oni.hasNext() ) { IGridNode otherNodes = oni.next(); - if ( otherNodes != pi ) + if( otherNodes != pi ) this.semiOpen.add( (IPathItem) otherNodes ); } } @@ -103,19 +103,19 @@ public class PathSegment return this.open.isEmpty(); } - private boolean useChannel(IPathItem start) + private boolean useDenseChannel( IPathItem start ) { IPathItem pi = start; - while (pi != null) + while( pi != null ) { - if ( !pi.canSupportMoreChannels() ) + if( !pi.canSupportMoreChannels() || pi.getFlags().contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) return false; pi = pi.getControllerRoute(); } pi = start; - while (pi != null) + while( pi != null ) { this.pgc.channelsByBlocks++; pi.incrementChannelCount( 1 ); @@ -126,19 +126,19 @@ public class PathSegment return true; } - private boolean useDenseChannel(IPathItem start) + private boolean useChannel( IPathItem start ) { IPathItem pi = start; - while (pi != null) + while( pi != null ) { - if ( !pi.canSupportMoreChannels() || pi.getFlags().contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) + if( !pi.canSupportMoreChannels() ) return false; pi = pi.getControllerRoute(); } pi = start; - while (pi != null) + while( pi != null ) { this.pgc.channelsByBlocks++; pi.incrementChannelCount( 1 ); @@ -148,5 +148,4 @@ public class PathSegment this.pgc.channelsInUse++; return true; } - } diff --git a/src/main/java/appeng/me/storage/AEExternalHandler.java b/src/main/java/appeng/me/storage/AEExternalHandler.java index ff16bb53a..1f61ee528 100644 --- a/src/main/java/appeng/me/storage/AEExternalHandler.java +++ b/src/main/java/appeng/me/storage/AEExternalHandler.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -31,45 +32,46 @@ import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.tile.misc.TileCondenser; + public class AEExternalHandler implements IExternalStorageHandler { @Override - public boolean canHandle(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc) + public boolean canHandle( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc ) { - if ( channel == StorageChannel.ITEMS && te instanceof ITileStorageMonitorable ) - return ((ITileStorageMonitorable) te).getMonitorable( d, mySrc ) != null; + if( channel == StorageChannel.ITEMS && te instanceof ITileStorageMonitorable ) + return ( (ITileStorageMonitorable) te ).getMonitorable( d, mySrc ) != null; return te instanceof TileCondenser; } @Override - public IMEInventory getInventory(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src) + public IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src ) { - if ( te instanceof TileCondenser ) + if( te instanceof TileCondenser ) { - if ( channel == StorageChannel.ITEMS ) + if( channel == StorageChannel.ITEMS ) return new VoidItemInventory( (TileCondenser) te ); else return new VoidFluidInventory( (TileCondenser) te ); } - if ( te instanceof ITileStorageMonitorable ) + if( te instanceof ITileStorageMonitorable ) { ITileStorageMonitorable iface = (ITileStorageMonitorable) te; IStorageMonitorable sm = iface.getMonitorable( d, src ); - if ( channel == StorageChannel.ITEMS && sm != null ) + if( channel == StorageChannel.ITEMS && sm != null ) { IMEInventory ii = sm.getItemInventory(); - if ( ii != null ) + if( ii != null ) return ii; } - if ( channel == StorageChannel.FLUIDS && sm != null ) + if( channel == StorageChannel.FLUIDS && sm != null ) { IMEInventory fi = sm.getFluidInventory(); - if ( fi != null ) + if( fi != null ) return fi; } } diff --git a/src/main/java/appeng/me/storage/CellInventory.java b/src/main/java/appeng/me/storage/CellInventory.java index c2083bbc8..5e38b4954 100644 --- a/src/main/java/appeng/me/storage/CellInventory.java +++ b/src/main/java/appeng/me/storage/CellInventory.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import java.util.HashSet; import net.minecraft.inventory.IInventory; @@ -43,6 +44,7 @@ import appeng.api.storage.data.IItemList; import appeng.util.Platform; import appeng.util.item.AEItemStack; + public class CellInventory implements ICellInventory { @@ -54,50 +56,285 @@ public class CellInventory implements ICellInventory static final String ITEM_PRE_FORMATTED_SLOT = "PF#"; static final String ITEM_PRE_FORMATTED_NAME = "PN"; static final String ITEM_PRE_FORMATTED_FUZZY = "FP"; - + private static final HashSet BLACK_LIST = new HashSet(); static protected String[] ITEM_SLOT_ARR; static protected String[] ITEM_SLOT_COUNT_ARR; - final protected NBTTagCompound tagCompound; + final protected ISaveProvider container; protected int MAX_ITEM_TYPES = 63; protected short storedItems = 0; protected int storedItemCount = 0; protected IItemList cellItems; - protected ItemStack i; protected IStorageCell CellType; - final protected ISaveProvider container; - - protected CellInventory(NBTTagCompound data, ISaveProvider container) { + protected CellInventory( NBTTagCompound data, ISaveProvider container ) + { this.tagCompound = data; this.container = container; } - protected void loadCellItems() + protected CellInventory( ItemStack o, ISaveProvider container ) throws AppEngException { - if ( this.cellItems == null ) - this.cellItems = AEApi.instance().storage().createItemList(); - - this.cellItems.resetStatus(); // clears totals and stuff. - - int types = (int) this.getStoredItemTypes(); - - for (int x = 0; x < types; x++) + if( ITEM_SLOT_ARR == null ) { - ItemStack t = ItemStack.loadItemStackFromNBT( this.tagCompound.getCompoundTag( ITEM_SLOT_ARR[x] ) ); - if ( t != null ) - { - t.stackSize = this.tagCompound.getInteger( ITEM_SLOT_COUNT_ARR[x] ); + ITEM_SLOT_ARR = new String[this.MAX_ITEM_TYPES]; + ITEM_SLOT_COUNT_ARR = new String[this.MAX_ITEM_TYPES]; - if ( t.stackSize > 0 ) + for( int x = 0; x < this.MAX_ITEM_TYPES; x++ ) + { + ITEM_SLOT_ARR[x] = ITEM_SLOT + x; + ITEM_SLOT_COUNT_ARR[x] = ITEM_SLOT_COUNT + x; + } + } + + if( o == null ) + { + throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); + } + + this.CellType = null; + this.i = o; + + Item type = this.i.getItem(); + if( type instanceof IStorageCell ) + { + this.CellType = (IStorageCell) this.i.getItem(); + this.MAX_ITEM_TYPES = this.CellType.getTotalTypes( this.i ); + } + + if( this.CellType == null ) + { + throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); + } + + if( !this.CellType.isStorageCell( this.i ) ) + { + throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); + } + + if( this.MAX_ITEM_TYPES > 63 ) + this.MAX_ITEM_TYPES = 63; + if( this.MAX_ITEM_TYPES < 1 ) + this.MAX_ITEM_TYPES = 1; + + this.container = container; + this.tagCompound = Platform.openNbtData( o ); + this.storedItems = this.tagCompound.getShort( ITEM_TYPE_TAG ); + this.storedItemCount = this.tagCompound.getInteger( ITEM_COUNT_TAG ); + this.cellItems = null; + } + + public static IMEInventoryHandler getCell( ItemStack o, ISaveProvider container2 ) + { + try + { + return new CellInventoryHandler( new CellInventory( o, container2 ) ); + } + catch( AppEngException e ) + { + return null; + } + } + + private static boolean isStorageCell( ItemStack i ) + { + if( i == null ) + { + return false; + } + + try + { + Item type = i.getItem(); + if( type instanceof IStorageCell ) + { + return !( (IStorageCell) type ).storableInStorageCell(); + } + } + catch( Throwable err ) + { + return true; + } + + return false; + } + + public static boolean isCell( ItemStack i ) + { + if( i == null ) + { + return false; + } + + Item type = i.getItem(); + if( type instanceof IStorageCell ) + { + return ( (IStorageCell) type ).isStorageCell( i ); + } + + return false; + } + + public static void addBasicBlackList( int itemID, int Meta ) + { + BLACK_LIST.add( ( Meta << Platform.DEF_OFFSET ) | itemID ); + } + + public static boolean isBlackListed( IAEItemStack input ) + { + if( BLACK_LIST.contains( ( OreDictionary.WILDCARD_VALUE << Platform.DEF_OFFSET ) | Item.getIdFromItem( input.getItem() ) ) ) + return true; + return BLACK_LIST.contains( ( input.getItemDamage() << Platform.DEF_OFFSET ) | Item.getIdFromItem( input.getItem() ) ); + } + + private boolean isEmpty( IMEInventory meInventory ) + { + return meInventory.getAvailableItems( AEApi.instance().storage().createItemList() ).isEmpty(); + } + + @Override + public IAEItemStack injectItems( IAEItemStack input, Actionable mode, BaseActionSource src ) + { + if( input == null ) + return null; + if( input.getStackSize() == 0 ) + return null; + + if( isBlackListed( input ) || this.CellType.isBlackListed( this.i, input ) ) + return input; + + ItemStack sharedItemStack = input.getItemStack(); + + if( CellInventory.isStorageCell( sharedItemStack ) ) + { + IMEInventory meInventory = getCell( sharedItemStack, null ); + if( meInventory != null && !this.isEmpty( meInventory ) ) + return input; + } + + IAEItemStack l = this.getCellItems().findPrecise( input ); + if( l != null ) + { + long remainingItemSlots = this.getRemainingItemCount(); + if( remainingItemSlots < 0 ) + return input; + + if( input.getStackSize() > remainingItemSlots ) + { + IAEItemStack r = input.copy(); + r.setStackSize( r.getStackSize() - remainingItemSlots ); + if( mode == Actionable.MODULATE ) { - this.cellItems.add( AEItemStack.create( t ) ); + l.setStackSize( l.getStackSize() + remainingItemSlots ); + this.updateItemCount( remainingItemSlots ); + this.saveChanges(); + } + return r; + } + else + { + if( mode == Actionable.MODULATE ) + { + l.setStackSize( l.getStackSize() + input.getStackSize() ); + this.updateItemCount( input.getStackSize() ); + this.saveChanges(); + } + return null; + } + } + + if( this.canHoldNewItem() ) // room for new type, and for at least one item! + { + int remainingItemCount = (int) this.getRemainingItemCount() - this.getBytesPerType() * 8; + if( remainingItemCount > 0 ) + { + if( input.getStackSize() > remainingItemCount ) + { + ItemStack toReturn = Platform.cloneItemStack( sharedItemStack ); + toReturn.stackSize = sharedItemStack.stackSize - remainingItemCount; + if( mode == Actionable.MODULATE ) + { + ItemStack toWrite = Platform.cloneItemStack( sharedItemStack ); + toWrite.stackSize = remainingItemCount; + + this.cellItems.add( AEItemStack.create( toWrite ) ); + this.updateItemCount( toWrite.stackSize ); + + this.saveChanges(); + } + return AEItemStack.create( toReturn ); + } + + if( mode == Actionable.MODULATE ) + { + this.updateItemCount( input.getStackSize() ); + this.cellItems.add( input ); + this.saveChanges(); + } + + return null; + } + } + + return input; + } + + @Override + public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) + { + if( request == null ) + return null; + + long size = Math.min( Integer.MAX_VALUE, request.getStackSize() ); + + IAEItemStack Results = null; + + IAEItemStack l = this.getCellItems().findPrecise( request ); + if( l != null ) + { + Results = l.copy(); + + if( l.getStackSize() <= size ) + { + Results.setStackSize( l.getStackSize() ); + if( mode == Actionable.MODULATE ) + { + this.updateItemCount( -l.getStackSize() ); + l.setStackSize( 0 ); + this.saveChanges(); + } + } + else + { + Results.setStackSize( size ); + if( mode == Actionable.MODULATE ) + { + l.setStackSize( l.getStackSize() - size ); + this.updateItemCount( -size ); + this.saveChanges(); } } } - // cellItems.clean(); + return Results; + } + + IItemList getCellItems() + { + if( this.cellItems == null ) + { + this.cellItems = AEApi.instance().storage().createItemList(); + this.loadCellItems(); + } + + return this.cellItems; + } + + private void updateItemCount( long delta ) + { + this.storedItemCount += delta; + this.tagCompound.setInteger( ITEM_COUNT_TAG, this.storedItemCount ); } void saveChanges() @@ -107,12 +344,12 @@ public class CellInventory implements ICellInventory // add new pretty stuff... int x = 0; - for (IAEItemStack v : this.cellItems) + for( IAEItemStack v : this.cellItems ) { itemCount += v.getStackSize(); NBTBase c = this.tagCompound.getTag( ITEM_SLOT_ARR[x] ); - if ( c instanceof NBTTagCompound ) + if( c instanceof NBTTagCompound ) { v.writeToNBT( (NBTTagCompound) c ); } @@ -140,20 +377,20 @@ public class CellInventory implements ICellInventory * if ( tagType instanceof NBTTagShort ) ((NBTTagShort) tagType).data = storedItems = (short) cellItems.size(); * else */ - if ( this.cellItems.isEmpty() ) + if( this.cellItems.isEmpty() ) { this.tagCompound.removeTag( ITEM_TYPE_TAG ); } else { - this.storedItems = ( short ) this.cellItems.size(); + this.storedItems = (short) this.cellItems.size(); this.tagCompound.setShort( ITEM_TYPE_TAG, this.storedItems ); } /* * if ( tagCount instanceof NBTTagInt ) ((NBTTagInt) tagCount).data = storedItemCount = itemCount; else */ - if ( itemCount == 0 ) + if( itemCount == 0 ) { this.tagCompound.removeTag( ITEM_COUNT_TAG ); } @@ -164,362 +401,46 @@ public class CellInventory implements ICellInventory } // clean any old crusty stuff... - for (; x < oldStoredItems && x < this.MAX_ITEM_TYPES; x++) + for(; x < oldStoredItems && x < this.MAX_ITEM_TYPES; x++ ) { this.tagCompound.removeTag( ITEM_SLOT_ARR[x] ); this.tagCompound.removeTag( ITEM_SLOT_COUNT_ARR[x] ); } - if ( this.container != null ) + if( this.container != null ) this.container.saveChanges( this ); } - protected CellInventory(ItemStack o, ISaveProvider container) throws AppEngException { - if ( ITEM_SLOT_ARR == null ) - { - ITEM_SLOT_ARR = new String[this.MAX_ITEM_TYPES]; - ITEM_SLOT_COUNT_ARR = new String[this.MAX_ITEM_TYPES]; - - for (int x = 0; x < this.MAX_ITEM_TYPES; x++) - { - ITEM_SLOT_ARR[x] = ITEM_SLOT + x; - ITEM_SLOT_COUNT_ARR[x] = ITEM_SLOT_COUNT + x; - } - } - - if ( o == null ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } - - this.CellType = null; - this.i = o; - - Item type = this.i.getItem(); - if ( type instanceof IStorageCell ) - { - this.CellType = (IStorageCell) this.i.getItem(); - this.MAX_ITEM_TYPES = this.CellType.getTotalTypes( this.i ); - } - - if ( this.CellType == null ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } - - if ( !this.CellType.isStorageCell( this.i ) ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } - - if ( this.MAX_ITEM_TYPES > 63 ) - this.MAX_ITEM_TYPES = 63; - if ( this.MAX_ITEM_TYPES < 1 ) - this.MAX_ITEM_TYPES = 1; - - this.container = container; - this.tagCompound = Platform.openNbtData( o ); - this.storedItems = this.tagCompound.getShort( ITEM_TYPE_TAG ); - this.storedItemCount = this.tagCompound.getInteger( ITEM_COUNT_TAG ); - this.cellItems = null; - } - - IItemList getCellItems() + protected void loadCellItems() { - if ( this.cellItems == null ) - { + if( this.cellItems == null ) this.cellItems = AEApi.instance().storage().createItemList(); - this.loadCellItems(); - } - return this.cellItems; - } + this.cellItems.resetStatus(); // clears totals and stuff. - @Override - public int getBytesPerType() - { - return this.CellType.BytePerType( this.i ); - } + int types = (int) this.getStoredItemTypes(); - @Override - public boolean canHoldNewItem() - { - long bytesFree = this.getFreeBytes(); - return (bytesFree > this.getBytesPerType() || (bytesFree == this.getBytesPerType() && this.getUnusedItemCount() > 0)) && this.getRemainingItemTypes() > 0; - } - - public static IMEInventoryHandler getCell(ItemStack o, ISaveProvider container2) - { - try + for( int x = 0; x < types; x++ ) { - return new CellInventoryHandler( new CellInventory( o, container2 ) ); - } - catch (AppEngException e) - { - return null; - } - } - - private static boolean isStorageCell(ItemStack i) - { - if ( i == null ) - { - return false; - } - - try - { - Item type = i.getItem(); - if ( type instanceof IStorageCell ) + ItemStack t = ItemStack.loadItemStackFromNBT( this.tagCompound.getCompoundTag( ITEM_SLOT_ARR[x] ) ); + if( t != null ) { - return !((IStorageCell) type).storableInStorageCell(); - } - } - catch (Throwable err) - { - return true; - } + t.stackSize = this.tagCompound.getInteger( ITEM_SLOT_COUNT_ARR[x] ); - return false; - } - - public static boolean isCell(ItemStack i) - { - if ( i == null ) - { - return false; - } - - Item type = i.getItem(); - if ( type instanceof IStorageCell ) - { - return ((IStorageCell) type).isStorageCell( i ); - } - - return false; - } - - @Override - public long getTotalBytes() - { - return this.CellType.getBytes( this.i ); - } - - @Override - public long getFreeBytes() - { - return this.getTotalBytes() - this.getUsedBytes(); - } - - @Override - public long getUsedBytes() - { - long bytesForItemCount = (this.getStoredItemCount() + this.getUnusedItemCount()) / 8; - return this.getStoredItemTypes() * this.getBytesPerType() + bytesForItemCount; - } - - @Override - public long getTotalItemTypes() - { - return this.MAX_ITEM_TYPES; - } - - @Override - public long getStoredItemTypes() - { - return this.storedItems; - } - - @Override - public long getStoredItemCount() - { - return this.storedItemCount; - } - - private void updateItemCount(long delta) - { - this.storedItemCount += delta; - this.tagCompound.setInteger( ITEM_COUNT_TAG, this.storedItemCount ); - } - - @Override - public long getRemainingItemTypes() - { - long basedOnStorage = this.getFreeBytes() / this.getBytesPerType(); - long baseOnTotal = this.getTotalItemTypes() - this.getStoredItemTypes(); - return basedOnStorage > baseOnTotal ? baseOnTotal : basedOnStorage; - } - - @Override - public long getRemainingItemCount() - { - long remaining = this.getFreeBytes() * 8 + this.getUnusedItemCount(); - return remaining > 0 ? remaining : 0; - } - - @Override - public int getUnusedItemCount() - { - int div = (int) (this.getStoredItemCount() % 8); - - if ( div == 0 ) - { - return 0; - } - - return 8 - div; - } - - private static final HashSet BLACK_LIST = new HashSet(); - - public static void addBasicBlackList(int itemID, int Meta) - { - BLACK_LIST.add( ( Meta << Platform.DEF_OFFSET ) | itemID ); - } - - public static boolean isBlackListed(IAEItemStack input) - { - if ( BLACK_LIST.contains( (OreDictionary.WILDCARD_VALUE << Platform.DEF_OFFSET) | Item.getIdFromItem( input.getItem() ) ) ) - return true; - return BLACK_LIST.contains( (input.getItemDamage() << Platform.DEF_OFFSET) | Item.getIdFromItem( input.getItem() ) ); - } - - private boolean isEmpty(IMEInventory meInventory) - { - return meInventory.getAvailableItems( AEApi.instance().storage().createItemList() ).isEmpty(); - } - - @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable mode, BaseActionSource src) - { - if ( input == null ) - return null; - if ( input.getStackSize() == 0 ) - return null; - - if ( isBlackListed( input ) || this.CellType.isBlackListed( this.i, input ) ) - return input; - - ItemStack sharedItemStack = input.getItemStack(); - - if ( CellInventory.isStorageCell( sharedItemStack ) ) - { - IMEInventory meInventory = getCell( sharedItemStack, null ); - if ( meInventory != null && !this.isEmpty( meInventory ) ) - return input; - } - - IAEItemStack l = this.getCellItems().findPrecise( input ); - if ( l != null ) - { - long remainingItemSlots = this.getRemainingItemCount(); - if ( remainingItemSlots < 0 ) - return input; - - if ( input.getStackSize() > remainingItemSlots ) - { - IAEItemStack r = input.copy(); - r.setStackSize( r.getStackSize() - remainingItemSlots ); - if ( mode == Actionable.MODULATE ) + if( t.stackSize > 0 ) { - l.setStackSize( l.getStackSize() + remainingItemSlots ); - this.updateItemCount( remainingItemSlots ); - this.saveChanges(); - } - return r; - } - else - { - if ( mode == Actionable.MODULATE ) - { - l.setStackSize( l.getStackSize() + input.getStackSize() ); - this.updateItemCount( input.getStackSize() ); - this.saveChanges(); - } - return null; - } - } - - if ( this.canHoldNewItem() ) // room for new type, and for at least one item! - { - int remainingItemCount = (int) this.getRemainingItemCount() - this.getBytesPerType() * 8; - if ( remainingItemCount > 0 ) - { - if ( input.getStackSize() > remainingItemCount ) - { - ItemStack toReturn = Platform.cloneItemStack( sharedItemStack ); - toReturn.stackSize = sharedItemStack.stackSize - remainingItemCount; - if ( mode == Actionable.MODULATE ) - { - ItemStack toWrite = Platform.cloneItemStack( sharedItemStack ); - toWrite.stackSize = remainingItemCount; - - this.cellItems.add( AEItemStack.create( toWrite ) ); - this.updateItemCount( toWrite.stackSize ); - - this.saveChanges(); - } - return AEItemStack.create( toReturn ); - } - - if ( mode == Actionable.MODULATE ) - { - this.updateItemCount( input.getStackSize() ); - this.cellItems.add( input ); - this.saveChanges(); - } - - return null; - } - } - - return input; - } - - @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) - { - if ( request == null ) - return null; - - long size = Math.min( Integer.MAX_VALUE, request.getStackSize() ); - - IAEItemStack Results = null; - - IAEItemStack l = this.getCellItems().findPrecise( request ); - if ( l != null ) - { - Results = l.copy(); - - if ( l.getStackSize() <= size ) - { - Results.setStackSize( l.getStackSize() ); - if ( mode == Actionable.MODULATE ) - { - this.updateItemCount( -l.getStackSize() ); - l.setStackSize( 0 ); - this.saveChanges(); - } - } - else - { - Results.setStackSize( size ); - if ( mode == Actionable.MODULATE ) - { - l.setStackSize( l.getStackSize() - size ); - this.updateItemCount( -size ); - this.saveChanges(); + this.cellItems.add( AEItemStack.create( t ) ); } } } - return Results; + // cellItems.clean(); } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { - for (IAEItemStack i : this.getCellItems()) + for( IAEItemStack i : this.getCellItems() ) out.add( i ); return out; @@ -531,6 +452,12 @@ public class CellInventory implements ICellInventory return StorageChannel.ITEMS; } + @Override + public ItemStack getItemStack() + { + return this.i; + } + @Override public double getIdleDrain() { @@ -556,19 +483,90 @@ public class CellInventory implements ICellInventory } @Override - public int getStatusForCell() + public int getBytesPerType() { - if ( this.canHoldNewItem() ) - return 1; - if ( this.getRemainingItemCount() > 0 ) - return 2; - return 3; + return this.CellType.BytePerType( this.i ); } @Override - public ItemStack getItemStack() + public boolean canHoldNewItem() { - return this.i; + long bytesFree = this.getFreeBytes(); + return ( bytesFree > this.getBytesPerType() || ( bytesFree == this.getBytesPerType() && this.getUnusedItemCount() > 0 ) ) && this.getRemainingItemTypes() > 0; } + @Override + public long getTotalBytes() + { + return this.CellType.getBytes( this.i ); + } + + @Override + public long getFreeBytes() + { + return this.getTotalBytes() - this.getUsedBytes(); + } + + @Override + public long getUsedBytes() + { + long bytesForItemCount = ( this.getStoredItemCount() + this.getUnusedItemCount() ) / 8; + return this.getStoredItemTypes() * this.getBytesPerType() + bytesForItemCount; + } + + @Override + public long getTotalItemTypes() + { + return this.MAX_ITEM_TYPES; + } + + @Override + public long getStoredItemCount() + { + return this.storedItemCount; + } + + @Override + public long getStoredItemTypes() + { + return this.storedItems; + } + + @Override + public long getRemainingItemTypes() + { + long basedOnStorage = this.getFreeBytes() / this.getBytesPerType(); + long baseOnTotal = this.getTotalItemTypes() - this.getStoredItemTypes(); + return basedOnStorage > baseOnTotal ? baseOnTotal : basedOnStorage; + } + + @Override + public long getRemainingItemCount() + { + long remaining = this.getFreeBytes() * 8 + this.getUnusedItemCount(); + return remaining > 0 ? remaining : 0; + } + + @Override + public int getUnusedItemCount() + { + int div = (int) ( this.getStoredItemCount() % 8 ); + + if( div == 0 ) + { + return 0; + } + + return 8 - div; + } + + @Override + public int getStatusForCell() + { + if( this.canHoldNewItem() ) + return 1; + if( this.getRemainingItemCount() > 0 ) + return 2; + return 3; + } } diff --git a/src/main/java/appeng/me/storage/CellInventoryHandler.java b/src/main/java/appeng/me/storage/CellInventoryHandler.java index cf58e4f02..85db34043 100644 --- a/src/main/java/appeng/me/storage/CellInventoryHandler.java +++ b/src/main/java/appeng/me/storage/CellInventoryHandler.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -38,30 +39,16 @@ import appeng.util.item.AEItemStack; import appeng.util.prioitylist.FuzzyPriorityList; import appeng.util.prioitylist.PrecisePriorityList; + public class CellInventoryHandler extends MEInventoryHandler implements ICellInventoryHandler { - NBTTagCompound openNbtData() + CellInventoryHandler( IMEInventory c ) { - return Platform.openNbtData( this.getCellInv().getItemStack() ); - } - - @Override - public ICellInventory getCellInv() - { - Object o = this.internal; - - if ( o instanceof MEPassThrough ) - o = ((MEPassThrough) o).getInternal(); - - return (ICellInventory) (o instanceof ICellInventory ? o : null); - } - - CellInventoryHandler(IMEInventory c) { super( c, StorageChannel.ITEMS ); ICellInventory ci = this.getCellInv(); - if ( ci != null ) + if( ci != null ) { IItemList priorityList = AEApi.instance().storage().createItemList(); @@ -72,40 +59,40 @@ public class CellInventoryHandler extends MEInventoryHandler imple boolean hasInverter = false; boolean hasFuzzy = false; - for (int x = 0; x < upgrades.getSizeInventory(); x++) + for( int x = 0; x < upgrades.getSizeInventory(); x++ ) { ItemStack is = upgrades.getStackInSlot( x ); - if ( is != null && is.getItem() instanceof IUpgradeModule ) + if( is != null && is.getItem() instanceof IUpgradeModule ) { - Upgrades u = ((IUpgradeModule) is.getItem()).getType( is ); - if ( u != null ) + Upgrades u = ( (IUpgradeModule) is.getItem() ).getType( is ); + if( u != null ) { - switch (u) + switch( u ) { - case FUZZY: - hasFuzzy = true; - break; - case INVERTER: - hasInverter = true; - break; - default: + case FUZZY: + hasFuzzy = true; + break; + case INVERTER: + hasInverter = true; + break; + default: } } } } - for (int x = 0; x < config.getSizeInventory(); x++) + for( int x = 0; x < config.getSizeInventory(); x++ ) { ItemStack is = config.getStackInSlot( x ); - if ( is != null ) + if( is != null ) priorityList.add( AEItemStack.create( is ) ); } this.setWhitelist( hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - if ( !priorityList.isEmpty() ) + if( !priorityList.isEmpty() ) { - if ( hasFuzzy ) + if( hasFuzzy ) this.setPartitionList( new FuzzyPriorityList( priorityList, fzMode ) ); else this.setPartitionList( new PrecisePriorityList( priorityList ) ); @@ -113,10 +100,21 @@ public class CellInventoryHandler extends MEInventoryHandler imple } } + @Override + public ICellInventory getCellInv() + { + Object o = this.internal; + + if( o instanceof MEPassThrough ) + o = ( (MEPassThrough) o ).getInternal(); + + return (ICellInventory) ( o instanceof ICellInventory ? o : null ); + } + @Override public boolean isPreformatted() { - return ! this.getPartitionList().isEmpty(); + return !this.getPartitionList().isEmpty(); } @Override @@ -131,14 +129,18 @@ public class CellInventoryHandler extends MEInventoryHandler imple return this.getWhitelist(); } - public int getStatusForCell() + NBTTagCompound openNbtData() { - int val = this.getCellInv().getStatusForCell(); - - if ( val == 1 && this.isPreformatted() ) - val = 2; - - return val; + return Platform.openNbtData( this.getCellInv().getItemStack() ); } + public int getStatusForCell() + { + int val = this.getCellInv().getStatusForCell(); + + if( val == 1 && this.isPreformatted() ) + val = 2; + + return val; + } } diff --git a/src/main/java/appeng/me/storage/CreativeCellInventory.java b/src/main/java/appeng/me/storage/CreativeCellInventory.java index 7c48d1e25..0a879a2f3 100644 --- a/src/main/java/appeng/me/storage/CreativeCellInventory.java +++ b/src/main/java/appeng/me/storage/CreativeCellInventory.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import net.minecraft.item.ItemStack; import appeng.api.AEApi; @@ -31,21 +32,17 @@ import appeng.api.storage.data.IItemList; import appeng.items.contents.CellConfig; import appeng.util.item.AEItemStack; + public class CreativeCellInventory implements IMEInventoryHandler { final IItemList itemListCache = AEApi.instance().storage().createItemList(); - public static IMEInventoryHandler getCell(ItemStack o) - { - return new CellInventoryHandler( new CreativeCellInventory( o ) ); - } - - protected CreativeCellInventory(ItemStack o) + protected CreativeCellInventory( ItemStack o ) { CellConfig cc = new CellConfig( o ); - for (ItemStack is : cc) - if ( is != null ) + for( ItemStack is : cc ) + if( is != null ) { IAEItemStack i = AEItemStack.create( is ); i.setStackSize( Integer.MAX_VALUE ); @@ -53,30 +50,35 @@ public class CreativeCellInventory implements IMEInventoryHandler } } + public static IMEInventoryHandler getCell( ItemStack o ) + { + return new CellInventoryHandler( new CreativeCellInventory( o ) ); + } + @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable mode, BaseActionSource src) + public IAEItemStack injectItems( IAEItemStack input, Actionable mode, BaseActionSource src ) { IAEItemStack local = this.itemListCache.findPrecise( input ); - if ( local == null ) + if( local == null ) return input; return null; } @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) + public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) { IAEItemStack local = this.itemListCache.findPrecise( request ); - if ( local == null ) + if( local == null ) return null; return request.copy(); } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { - for (IAEItemStack ais : this.itemListCache) + for( IAEItemStack ais : this.itemListCache ) out.add( ais ); return out; } @@ -94,13 +96,13 @@ public class CreativeCellInventory implements IMEInventoryHandler } @Override - public boolean isPrioritized(IAEItemStack input) + public boolean isPrioritized( IAEItemStack input ) { return this.itemListCache.findPrecise( input ) != null; } @Override - public boolean canAccept(IAEItemStack input) + public boolean canAccept( IAEItemStack input ) { return this.itemListCache.findPrecise( input ) != null; } @@ -118,9 +120,8 @@ public class CreativeCellInventory implements IMEInventoryHandler } @Override - public boolean validForPass(int i) + public boolean validForPass( int i ) { return true; } - } diff --git a/src/main/java/appeng/me/storage/DriveWatcher.java b/src/main/java/appeng/me/storage/DriveWatcher.java index e6e32bb17..dede97918 100644 --- a/src/main/java/appeng/me/storage/DriveWatcher.java +++ b/src/main/java/appeng/me/storage/DriveWatcher.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import net.minecraft.item.ItemStack; import appeng.api.config.Actionable; @@ -27,6 +28,7 @@ import appeng.api.storage.ICellHandler; import appeng.api.storage.IMEInventory; import appeng.api.storage.data.IAEStack; + public class DriveWatcher> extends MEInventoryHandler { @@ -35,7 +37,8 @@ public class DriveWatcher> extends MEInventoryHandler final ICellHandler handler; final IChestOrDrive cord; - public DriveWatcher(IMEInventory i, ItemStack is, ICellHandler han, IChestOrDrive cod) { + public DriveWatcher( IMEInventory i, ItemStack is, ICellHandler han, IChestOrDrive cod ) + { super( i, i.getChannel() ); this.is = is; this.handler = han; @@ -43,17 +46,17 @@ public class DriveWatcher> extends MEInventoryHandler } @Override - public T injectItems(T input, Actionable type, BaseActionSource src) + public T injectItems( T input, Actionable type, BaseActionSource src ) { long size = input.getStackSize(); T a = super.injectItems( input, type, src ); - if ( a == null || a.getStackSize() != size ) + if( a == null || a.getStackSize() != size ) { int newStatus = this.handler.getStatusForCell( this.is, this.getInternal() ); - if ( newStatus != this.oldStatus ) + if( newStatus != this.oldStatus ) { this.cord.blinkCell( this.getSlot() ); } @@ -63,15 +66,15 @@ public class DriveWatcher> extends MEInventoryHandler } @Override - public T extractItems(T request, Actionable type, BaseActionSource src) + public T extractItems( T request, Actionable type, BaseActionSource src ) { T a = super.extractItems( request, type, src ); - if ( a != null ) + if( a != null ) { int newStatus = this.handler.getStatusForCell( this.is, this.getInternal() ); - if ( newStatus != this.oldStatus ) + if( newStatus != this.oldStatus ) { this.cord.blinkCell( this.getSlot() ); } diff --git a/src/main/java/appeng/me/storage/ItemWatcher.java b/src/main/java/appeng/me/storage/ItemWatcher.java index 64933fe27..e3ebd7d09 100644 --- a/src/main/java/appeng/me/storage/ItemWatcher.java +++ b/src/main/java/appeng/me/storage/ItemWatcher.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import java.util.Collection; import java.util.HashSet; import java.util.Iterator; @@ -27,12 +28,134 @@ import appeng.api.networking.storage.IStackWatcherHost; import appeng.api.storage.data.IAEStack; import appeng.me.cache.GridStorageCache; + /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ public class ItemWatcher implements IStackWatcher { + final GridStorageCache gsc; + final IStackWatcherHost myObject; + final HashSet myInterests = new HashSet(); + + public ItemWatcher( GridStorageCache cache, IStackWatcherHost host ) + { + this.gsc = cache; + this.myObject = host; + } + + public IStackWatcherHost getHost() + { + return this.myObject; + } + + @Override + public int size() + { + return this.myInterests.size(); + } + + @Override + public boolean isEmpty() + { + return this.myInterests.isEmpty(); + } + + @Override + public boolean contains( Object o ) + { + return this.myInterests.contains( o ); + } + + @Override + public Iterator iterator() + { + return new ItemWatcherIterator( this, this.myInterests.iterator() ); + } + + @Override + public Object[] toArray() + { + return this.myInterests.toArray(); + } + + @Override + public T[] toArray( T[] a ) + { + return this.myInterests.toArray( a ); + } + + @Override + public boolean add( IAEStack e ) + { + if( this.myInterests.contains( e ) ) + return false; + + return this.myInterests.add( e.copy() ) && this.gsc.interestManager.put( e, this ); + } + + @Override + public boolean remove( Object o ) + { + return this.myInterests.remove( o ) && this.gsc.interestManager.remove( (IAEStack) o, this ); + } + + @Override + public boolean containsAll( Collection c ) + { + return this.myInterests.containsAll( c ); + } + + @Override + public boolean addAll( Collection c ) + { + boolean didChange = false; + + for( IAEStack o : c ) + didChange = this.add( o ) || didChange; + + return didChange; + } + + @Override + public boolean removeAll( Collection c ) + { + boolean didSomething = false; + for( Object o : c ) + didSomething = this.remove( o ) || didSomething; + return didSomething; + } + + @Override + public boolean retainAll( Collection c ) + { + boolean changed = false; + Iterator i = this.iterator(); + + while( i.hasNext() ) + { + if( !c.contains( i.next() ) ) + { + i.remove(); + changed = true; + } + } + + return changed; + } + + @Override + public void clear() + { + Iterator i = this.myInterests.iterator(); + while( i.hasNext() ) + { + this.gsc.interestManager.remove( i.next(), this ); + i.remove(); + } + } + class ItemWatcherIterator implements Iterator { @@ -40,7 +163,8 @@ public class ItemWatcher implements IStackWatcher final Iterator interestIterator; IAEStack myLast; - public ItemWatcherIterator(ItemWatcher parent, Iterator i) { + public ItemWatcherIterator( ItemWatcher parent, Iterator i ) + { this.watcher = parent; this.interestIterator = i; } @@ -63,127 +187,5 @@ public class ItemWatcher implements IStackWatcher ItemWatcher.this.gsc.interestManager.remove( this.myLast, this.watcher ); this.interestIterator.remove(); } - } - - final GridStorageCache gsc; - final IStackWatcherHost myObject; - final HashSet myInterests = new HashSet(); - - public ItemWatcher(GridStorageCache cache, IStackWatcherHost host) { - this.gsc = cache; - this.myObject = host; - } - - public IStackWatcherHost getHost() - { - return this.myObject; - } - - @Override - public boolean add(IAEStack e) - { - if ( this.myInterests.contains( e ) ) - return false; - - return this.myInterests.add( e.copy() ) && this.gsc.interestManager.put( e, this ); - } - - @Override - public boolean addAll(Collection c) - { - boolean didChange = false; - - for (IAEStack o : c) - didChange = this.add( o ) || didChange; - - return didChange; - } - - @Override - public void clear() - { - Iterator i = this.myInterests.iterator(); - while (i.hasNext()) - { - this.gsc.interestManager.remove( i.next(), this ); - i.remove(); - } - } - - @Override - public boolean contains(Object o) - { - return this.myInterests.contains( o ); - } - - @Override - public boolean containsAll(Collection c) - { - return this.myInterests.containsAll( c ); - } - - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } - - @Override - public Iterator iterator() - { - return new ItemWatcherIterator( this, this.myInterests.iterator() ); - } - - @Override - public boolean remove(Object o) - { - return this.myInterests.remove( o ) && this.gsc.interestManager.remove( (IAEStack)o, this ); - } - - @Override - public boolean removeAll(Collection c) - { - boolean didSomething = false; - for (Object o : c) - didSomething = this.remove( o ) || didSomething; - return didSomething; - } - - @Override - public boolean retainAll(Collection c) - { - boolean changed = false; - Iterator i = this.iterator(); - - while (i.hasNext()) - { - if ( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } - - return changed; - } - - @Override - public int size() - { - return this.myInterests.size(); - } - - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } - - @Override - public T[] toArray(T[] a) - { - return this.myInterests.toArray( a ); - } - } diff --git a/src/main/java/appeng/me/storage/MEIInventoryWrapper.java b/src/main/java/appeng/me/storage/MEIInventoryWrapper.java index 94af9e1d9..e77460415 100644 --- a/src/main/java/appeng/me/storage/MEIInventoryWrapper.java +++ b/src/main/java/appeng/me/storage/MEIInventoryWrapper.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -31,64 +32,60 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.item.AEItemStack; + public class MEIInventoryWrapper implements IMEInventory { protected final IInventory target; protected final InventoryAdaptor adaptor; - public MEIInventoryWrapper(IInventory m, InventoryAdaptor ia) { + public MEIInventoryWrapper( IInventory m, InventoryAdaptor ia ) + { this.target = m; this.adaptor = ia; } @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public IAEItemStack injectItems(IAEItemStack iox, Actionable mode, BaseActionSource src) + public IAEItemStack injectItems( IAEItemStack iox, Actionable mode, BaseActionSource src ) { ItemStack input = iox.getItemStack(); - if ( this.adaptor != null ) + if( this.adaptor != null ) { ItemStack is = mode == Actionable.SIMULATE ? this.adaptor.simulateAdd( input ) : this.adaptor.addItems( input ); - if ( is == null ) + if( is == null ) return null; return AEItemStack.create( is ); } ItemStack out = Platform.cloneItemStack( input ); - if ( mode == Actionable.MODULATE ) // absolutely no need for a first run in simulate mode. + if( mode == Actionable.MODULATE ) // absolutely no need for a first run in simulate mode. { - for (int x = 0; x < this.target.getSizeInventory(); x++) + for( int x = 0; x < this.target.getSizeInventory(); x++ ) { ItemStack t = this.target.getStackInSlot( x ); - if ( Platform.isSameItem( t, input ) ) + if( Platform.isSameItem( t, input ) ) { int oriStack = t.stackSize; t.stackSize += out.stackSize; this.target.setInventorySlotContents( x, t ); - if ( t.stackSize > this.target.getInventoryStackLimit() ) + if( t.stackSize > this.target.getInventoryStackLimit() ) { t.stackSize = this.target.getInventoryStackLimit(); } - if ( t.stackSize > t.getMaxStackSize() ) + if( t.stackSize > t.getMaxStackSize() ) { t.stackSize = t.getMaxStackSize(); } out.stackSize -= t.stackSize - oriStack; - if ( out.stackSize <= 0 ) + if( out.stackSize <= 0 ) { return null; } @@ -96,25 +93,25 @@ public class MEIInventoryWrapper implements IMEInventory } } - for (int x = 0; x < this.target.getSizeInventory(); x++) + for( int x = 0; x < this.target.getSizeInventory(); x++ ) { ItemStack t = this.target.getStackInSlot( x ); - if ( t == null ) + if( t == null ) { t = Platform.cloneItemStack( input ); t.stackSize = out.stackSize; - if ( t.stackSize > this.target.getInventoryStackLimit() ) + if( t.stackSize > this.target.getInventoryStackLimit() ) { t.stackSize = this.target.getInventoryStackLimit(); } out.stackSize -= t.stackSize; - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) this.target.setInventorySlotContents( x, t ); - if ( out.stackSize <= 0 ) + if( out.stackSize <= 0 ) { return null; } @@ -125,21 +122,21 @@ public class MEIInventoryWrapper implements IMEInventory } @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) + public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) { ItemStack Gathered = null; ItemStack Req = request.getItemStack(); int request_stackSize = Req.stackSize; - if ( request_stackSize > Req.getMaxStackSize() ) + if( request_stackSize > Req.getMaxStackSize() ) { request_stackSize = Req.getMaxStackSize(); } Req.stackSize = request_stackSize; - if ( this.adaptor != null ) + if( this.adaptor != null ) { Gathered = this.adaptor.removeItems( Req.stackSize, Req, null ); } @@ -149,22 +146,22 @@ public class MEIInventoryWrapper implements IMEInventory Gathered.stackSize = 0; // try to find matching inventories that already have it... - for (int x = 0; x < this.target.getSizeInventory(); x++) + for( int x = 0; x < this.target.getSizeInventory(); x++ ) { ItemStack sub = this.target.getStackInSlot( x ); - if ( Platform.isSameItem( sub, Req ) ) + if( Platform.isSameItem( sub, Req ) ) { int reqNum = Req.stackSize; - if ( reqNum > sub.stackSize ) + if( reqNum > sub.stackSize ) { reqNum = Req.stackSize; } ItemStack retrieved = null; - if ( sub.stackSize < Req.stackSize ) + if( sub.stackSize < Req.stackSize ) { retrieved = Platform.cloneItemStack( sub ); sub.stackSize = 0; @@ -174,38 +171,37 @@ public class MEIInventoryWrapper implements IMEInventory retrieved = sub.splitStack( Req.stackSize ); } - if ( sub.stackSize <= 0 ) + if( sub.stackSize <= 0 ) this.target.setInventorySlotContents( x, null ); else this.target.setInventorySlotContents( x, sub ); - if ( retrieved != null ) + if( retrieved != null ) { Gathered.stackSize += retrieved.stackSize; Req.stackSize -= retrieved.stackSize; } - if ( request_stackSize == Gathered.stackSize ) + if( request_stackSize == Gathered.stackSize ) { return AEItemStack.create( Gathered ); } } } - if ( Gathered.stackSize == 0 ) + if( Gathered.stackSize == 0 ) { return null; } - } return AEItemStack.create( Gathered ); } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { - for (int x = 0; x < this.target.getSizeInventory(); x++) + for( int x = 0; x < this.target.getSizeInventory(); x++ ) { out.addStorage( AEItemStack.create( this.target.getStackInSlot( x ) ) ); } @@ -213,4 +209,9 @@ public class MEIInventoryWrapper implements IMEInventory return out; } + @Override + public StorageChannel getChannel() + { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/me/storage/MEInventoryHandler.java b/src/main/java/appeng/me/storage/MEInventoryHandler.java index 461d855b3..9ec4d25bd 100644 --- a/src/main/java/appeng/me/storage/MEInventoryHandler.java +++ b/src/main/java/appeng/me/storage/MEInventoryHandler.java @@ -36,10 +36,9 @@ import appeng.util.prioitylist.IPartitionList; public class MEInventoryHandler> implements IMEInventoryHandler { - final StorageChannel channel; final protected IMEMonitor monitor; final protected IMEInventoryHandler internal; - + final StorageChannel channel; private int myPriority; private IncludeExclude myWhitelist; private AccessRestriction myAccess; @@ -53,12 +52,12 @@ public class MEInventoryHandler> implements IMEInventoryHa { this.channel = channel; - if ( i instanceof IMEInventoryHandler ) - this.internal = ( IMEInventoryHandler ) i; + if( i instanceof IMEInventoryHandler ) + this.internal = (IMEInventoryHandler) i; else this.internal = new MEPassThrough( i, channel ); - this.monitor = this.internal instanceof IMEMonitor ? ( IMEMonitor ) this.internal : null; + this.monitor = this.internal instanceof IMEMonitor ? (IMEMonitor) this.internal : null; this.myPriority = 0; this.myWhitelist = IncludeExclude.WHITELIST; @@ -66,17 +65,6 @@ public class MEInventoryHandler> implements IMEInventoryHa this.myPartitionList = new DefaultPriorityList(); } - @Override - public int getPriority() - { - return this.myPriority; - } - - public void setPriority( int myPriority ) - { - this.myPriority = myPriority; - } - public IncludeExclude getWhitelist() { return this.myWhitelist; @@ -113,7 +101,7 @@ public class MEInventoryHandler> implements IMEInventoryHa @Override public T injectItems( T input, Actionable type, BaseActionSource src ) { - if ( !this.canAccept( input ) ) + if( !this.canAccept( input ) ) return input; return this.internal.injectItems( input, type, src ); @@ -122,7 +110,7 @@ public class MEInventoryHandler> implements IMEInventoryHa @Override public T extractItems( T request, Actionable type, BaseActionSource src ) { - if ( !this.hasReadAccess ) + if( !this.hasReadAccess ) return null; return this.internal.extractItems( request, type, src ); @@ -131,7 +119,7 @@ public class MEInventoryHandler> implements IMEInventoryHa @Override public IItemList getAvailableItems( IItemList out ) { - if ( !this.hasReadAccess ) + if( !this.hasReadAccess ) return out; return this.internal.getAvailableItems( out ); @@ -152,7 +140,7 @@ public class MEInventoryHandler> implements IMEInventoryHa @Override public boolean isPrioritized( T input ) { - if ( this.myWhitelist == IncludeExclude.WHITELIST ) + if( this.myWhitelist == IncludeExclude.WHITELIST ) return this.myPartitionList.isListed( input ) || this.internal.isPrioritized( input ); return false; } @@ -160,31 +148,41 @@ public class MEInventoryHandler> implements IMEInventoryHa @Override public boolean canAccept( T input ) { - if ( !this.hasWriteAccess ) + if( !this.hasWriteAccess ) return false; - if ( this.myWhitelist == IncludeExclude.BLACKLIST && this.myPartitionList.isListed( input ) ) + if( this.myWhitelist == IncludeExclude.BLACKLIST && this.myPartitionList.isListed( input ) ) return false; - if ( this.myPartitionList.isEmpty() || this.myWhitelist == IncludeExclude.BLACKLIST ) + if( this.myPartitionList.isEmpty() || this.myWhitelist == IncludeExclude.BLACKLIST ) return this.internal.canAccept( input ); return this.myPartitionList.isListed( input ) && this.internal.canAccept( input ); } + @Override + public int getPriority() + { + return this.myPriority; + } + + public void setPriority( int myPriority ) + { + this.myPriority = myPriority; + } + @Override public int getSlot() { return this.internal.getSlot(); } - public IMEInventory getInternal() - { - return this.internal; - } - @Override public boolean validForPass( int i ) { return true; } + public IMEInventory getInternal() + { + return this.internal; + } } diff --git a/src/main/java/appeng/me/storage/MEMonitorIInventory.java b/src/main/java/appeng/me/storage/MEMonitorIInventory.java index eff69de7a..43098b625 100644 --- a/src/main/java/appeng/me/storage/MEMonitorIInventory.java +++ b/src/main/java/appeng/me/storage/MEMonitorIInventory.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; @@ -42,70 +43,48 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.inv.ItemSlot; + public class MEMonitorIInventory implements IMEMonitor { - static class CachedItemStack - { - - public CachedItemStack(ItemStack is) - { - if ( is == null ) - { - this.itemStack = null; - this.aeStack = null; - } - else - { - this.itemStack = is.copy(); - this.aeStack = AEApi.instance().storage().createItemStack( is ); - } - } - - final ItemStack itemStack; - final IAEItemStack aeStack; - } - final InventoryAdaptor adaptor; - - private final NavigableMap memory; final IItemList list = AEApi.instance().storage().createItemList(); final HashMap, Object> listeners = new HashMap, Object>(); - + private final NavigableMap memory; public BaseActionSource mySource; public StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; - @Override - public void addListener(IMEMonitorHandlerReceiver l, Object verificationToken) - { - this.listeners.put( l, verificationToken ); - } - - @Override - public void removeListener(IMEMonitorHandlerReceiver l) - { - this.listeners.remove( l ); - } - - public MEMonitorIInventory(InventoryAdaptor adaptor) + public MEMonitorIInventory( InventoryAdaptor adaptor ) { this.adaptor = adaptor; this.memory = new ConcurrentSkipListMap(); } @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable type, BaseActionSource src) + public void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ) + { + this.listeners.put( l, verificationToken ); + } + + @Override + public void removeListener( IMEMonitorHandlerReceiver l ) + { + this.listeners.remove( l ); + } + + @Override + public IAEItemStack injectItems( IAEItemStack input, Actionable type, BaseActionSource src ) { ItemStack out = null; - if ( type == Actionable.SIMULATE ) + if( type == Actionable.SIMULATE ) out = this.adaptor.simulateAdd( input.getItemStack() ); else out = this.adaptor.addItems( input.getItemStack() ); this.onTick(); - if ( out == null ) + if( out == null ) return null; // better then doing construction from scratch :3 @@ -114,6 +93,146 @@ public class MEMonitorIInventory implements IMEMonitor return o; } + @Override + public IAEItemStack extractItems( IAEItemStack request, Actionable type, BaseActionSource src ) + { + ItemStack out = null; + + if( type == Actionable.SIMULATE ) + out = this.adaptor.simulateRemove( (int) request.getStackSize(), request.getItemStack(), null ); + else + out = this.adaptor.removeItems( (int) request.getStackSize(), request.getItemStack(), null ); + + if( out == null ) + return null; + + // better then doing construction from scratch :3 + IAEItemStack o = request.copy(); + o.setStackSize( out.stackSize ); + + this.onTick(); + + return o; + } + + @Override + public StorageChannel getChannel() + { + return StorageChannel.ITEMS; + } + + public TickRateModulation onTick() + { + boolean changed = false; + + LinkedList changes = new LinkedList(); + + int high = 0; + this.list.resetStatus(); + for( ItemSlot is : this.adaptor ) + { + CachedItemStack old = this.memory.get( is.slot ); + high = Math.max( high, is.slot ); + + ItemStack newIS = !is.isExtractable && this.mode == StorageFilter.EXTRACTABLE_ONLY ? null : is.getItemStack(); + ItemStack oldIS = old == null ? null : old.itemStack; + + if( this.isDifferent( newIS, oldIS ) ) + { + CachedItemStack cis = new CachedItemStack( is.getItemStack() ); + this.memory.put( is.slot, cis ); + + if( old != null && old.aeStack != null ) + { + old.aeStack.setStackSize( -old.aeStack.getStackSize() ); + changes.add( old.aeStack ); + } + + if( cis.aeStack != null ) + { + changes.add( cis.aeStack ); + this.list.add( cis.aeStack ); + } + + changed = true; + } + else + { + int newSize = ( newIS == null ? 0 : newIS.stackSize ); + int diff = newSize - ( oldIS == null ? 0 : oldIS.stackSize ); + + IAEItemStack stack = ( old == null || old.aeStack == null ? AEApi.instance().storage().createItemStack( newIS ) : old.aeStack.copy() ); + if( stack != null ) + { + stack.setStackSize( newSize ); + this.list.add( stack ); + } + + if( diff != 0 && stack != null ) + { + CachedItemStack cis = new CachedItemStack( is.getItemStack() ); + this.memory.put( is.slot, cis ); + + IAEItemStack a = stack.copy(); + a.setStackSize( diff ); + changes.add( a ); + changed = true; + } + } + } + + // detect dropped items; should fix non IISided Inventory Changes. + NavigableMap end = this.memory.tailMap( high, false ); + if( !end.isEmpty() ) + { + for( CachedItemStack cis : end.values() ) + { + if( cis != null && cis.aeStack != null ) + { + IAEItemStack a = cis.aeStack.copy(); + a.setStackSize( -a.getStackSize() ); + changes.add( a ); + changed = true; + } + } + end.clear(); + } + + if( !changes.isEmpty() ) + this.postDifference( changes ); + + return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; + } + + private boolean isDifferent( ItemStack a, ItemStack b ) + { + if( a == b && b == null ) + return false; + + if( ( a == null && b != null ) || ( a != null && b == null ) ) + return true; + + return !Platform.isSameItemPrecise( a, b ); + } + + private void postDifference( Iterable a ) + { + // AELog.info( a.getItemStack().getUnlocalizedName() + " @ " + a.getStackSize() ); + if( a != null ) + { + Iterator, Object>> i = this.listeners.entrySet().iterator(); + while( i.hasNext() ) + { + Entry, Object> l = i.next(); + IMEMonitorHandlerReceiver key = l.getKey(); + if( key.isValid( l.getValue() ) ) + key.postChange( this, a, this.mySource ); + else + i.remove(); + } + } + } + @Override public AccessRestriction getAccess() { @@ -121,13 +240,13 @@ public class MEMonitorIInventory implements IMEMonitor } @Override - public boolean isPrioritized(IAEItemStack input) + public boolean isPrioritized( IAEItemStack input ) { return false; } @Override - public boolean canAccept(IAEItemStack input) + public boolean canAccept( IAEItemStack input ) { return true; } @@ -145,164 +264,44 @@ public class MEMonitorIInventory implements IMEMonitor } @Override - public IItemList getStorageList() + public boolean validForPass( int i ) { - return this.list; + return true; } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { - for (CachedItemStack is : this.memory.values()) + for( CachedItemStack is : this.memory.values() ) out.addStorage( is.aeStack ); return out; } @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable type, BaseActionSource src) + public IItemList getStorageList() { - ItemStack out = null; - - if ( type == Actionable.SIMULATE ) - out = this.adaptor.simulateRemove( (int) request.getStackSize(), request.getItemStack(), null ); - else - out = this.adaptor.removeItems( (int) request.getStackSize(), request.getItemStack(), null ); - - if ( out == null ) - return null; - - // better then doing construction from scratch :3 - IAEItemStack o = request.copy(); - o.setStackSize( out.stackSize ); - - this.onTick(); - - return o; + return this.list; } - public TickRateModulation onTick() + static class CachedItemStack { - boolean changed = false; - LinkedList changes = new LinkedList(); + final ItemStack itemStack; + final IAEItemStack aeStack; - int high = 0; - this.list.resetStatus(); - for (ItemSlot is : this.adaptor) + public CachedItemStack( ItemStack is ) { - CachedItemStack old = this.memory.get( is.slot ); - high = Math.max( high, is.slot ); - - ItemStack newIS = !is.isExtractable && this.mode == StorageFilter.EXTRACTABLE_ONLY ? null : is.getItemStack(); - ItemStack oldIS = old == null ? null : old.itemStack; - - if ( this.isDifferent( newIS, oldIS ) ) + if( is == null ) { - CachedItemStack cis = new CachedItemStack( is.getItemStack() ); - this.memory.put( is.slot, cis ); - - if ( old != null && old.aeStack != null ) - { - old.aeStack.setStackSize( -old.aeStack.getStackSize() ); - changes.add( old.aeStack ); - } - - if ( cis.aeStack != null ) - { - changes.add( cis.aeStack ); - this.list.add( cis.aeStack ); - } - - changed = true; + this.itemStack = null; + this.aeStack = null; } else { - int newSize = (newIS == null ? 0 : newIS.stackSize); - int diff = newSize - (oldIS == null ? 0 : oldIS.stackSize); - - IAEItemStack stack = (old == null || old.aeStack == null ? AEApi.instance().storage().createItemStack( newIS ) : old.aeStack.copy()); - if ( stack != null ) - { - stack.setStackSize( newSize ); - this.list.add( stack ); - } - - if ( diff != 0 && stack != null ) - { - CachedItemStack cis = new CachedItemStack( is.getItemStack() ); - this.memory.put( is.slot, cis ); - - IAEItemStack a = stack.copy(); - a.setStackSize( diff ); - changes.add( a ); - changed = true; - } - } - } - - // detect dropped items; should fix non IISided Inventory Changes. - NavigableMap end = this.memory.tailMap( high, false ); - if ( !end.isEmpty() ) - { - for (CachedItemStack cis : end.values()) - { - if ( cis != null && cis.aeStack != null ) - { - IAEItemStack a = cis.aeStack.copy(); - a.setStackSize( -a.getStackSize() ); - changes.add( a ); - changed = true; - } - } - end.clear(); - } - - if ( !changes.isEmpty() ) - this.postDifference( changes ); - - return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; - } - - private boolean isDifferent(ItemStack a, ItemStack b) - { - if ( a == b && b == null ) - return false; - - if ( (a == null && b != null) || (a != null && b == null) ) - return true; - - return !Platform.isSameItemPrecise( a, b ); - } - - private void postDifference(Iterable a) - { - // AELog.info( a.getItemStack().getUnlocalizedName() + " @ " + a.getStackSize() ); - if ( a != null ) - { - Iterator, Object>> i = this.listeners.entrySet().iterator(); - while (i.hasNext()) - { - Entry, Object> l = i.next(); - IMEMonitorHandlerReceiver key = l.getKey(); - if ( key.isValid( l.getValue() ) ) - key.postChange( this, a, this.mySource ); - else - i.remove(); + this.itemStack = is.copy(); + this.aeStack = AEApi.instance().storage().createItemStack( is ); } } } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public boolean validForPass(int i) - { - return true; - } - } diff --git a/src/main/java/appeng/me/storage/MEMonitorPassThrough.java b/src/main/java/appeng/me/storage/MEMonitorPassThrough.java index b697e9164..467f6486f 100644 --- a/src/main/java/appeng/me/storage/MEMonitorPassThrough.java +++ b/src/main/java/appeng/me/storage/MEMonitorPassThrough.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; @@ -33,58 +34,57 @@ import appeng.api.storage.data.IItemList; import appeng.util.Platform; import appeng.util.inv.ItemListIgnoreCrafting; + public class MEMonitorPassThrough> extends MEPassThrough implements IMEMonitor, IMEMonitorHandlerReceiver { final HashMap, Object> listeners = new HashMap, Object>(); + public BaseActionSource changeSource; IMEMonitor monitor; - public BaseActionSource changeSource; - - public MEMonitorPassThrough(IMEInventory i, StorageChannel channel) { + public MEMonitorPassThrough( IMEInventory i, StorageChannel channel ) + { super( i, channel ); - if ( i instanceof IMEMonitor ) + if( i instanceof IMEMonitor ) this.monitor = (IMEMonitor) i; } @Override - public void setInternal(IMEInventory i) + public void setInternal( IMEInventory i ) { - if ( this.monitor != null ) + if( this.monitor != null ) this.monitor.removeListener( this ); this.monitor = null; - IItemList before = this.getInternal() == null ? this.channel.createList() : this.getInternal() - .getAvailableItems( new ItemListIgnoreCrafting( this.channel.createList() ) ); + IItemList before = this.getInternal() == null ? this.channel.createList() : this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( this.channel.createList() ) ); super.setInternal( i ); - if ( i instanceof IMEMonitor ) + if( i instanceof IMEMonitor ) this.monitor = (IMEMonitor) i; - IItemList after = this.getInternal() == null ? this.channel.createList() : this.getInternal() - .getAvailableItems( new ItemListIgnoreCrafting( this.channel.createList() ) ); + IItemList after = this.getInternal() == null ? this.channel.createList() : this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( this.channel.createList() ) ); - if ( this.monitor != null ) + if( this.monitor != null ) this.monitor.addListener( this, this.monitor ); Platform.postListChanges( before, after, this, this.changeSource ); } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { super.getAvailableItems( new ItemListIgnoreCrafting( out ) ); return out; } @Override - public void addListener(IMEMonitorHandlerReceiver l, Object verificationToken) + public void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ) { this.listeners.put( l, verificationToken ); } @Override - public void removeListener(IMEMonitorHandlerReceiver l) + public void removeListener( IMEMonitorHandlerReceiver l ) { this.listeners.remove( l ); } @@ -92,7 +92,7 @@ public class MEMonitorPassThrough> extends MEPassThrough getStorageList() { - if ( this.monitor == null ) + if( this.monitor == null ) { IItemList out = this.channel.createList(); this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( out ) ); @@ -102,20 +102,20 @@ public class MEMonitorPassThrough> extends MEPassThrough monitor, Iterable change, BaseActionSource source) + public void postChange( IBaseMonitor monitor, Iterable change, BaseActionSource source ) { Iterator, Object>> i = this.listeners.entrySet().iterator(); - while (i.hasNext()) + while( i.hasNext() ) { Entry, Object> e = i.next(); IMEMonitorHandlerReceiver receiver = e.getKey(); - if ( receiver.isValid( e.getValue() ) ) + if( receiver.isValid( e.getValue() ) ) receiver.postChange( this, change, source ); else i.remove(); @@ -126,11 +126,11 @@ public class MEMonitorPassThrough> extends MEPassThrough, Object>> i = this.listeners.entrySet().iterator(); - while (i.hasNext()) + while( i.hasNext() ) { Entry, Object> e = i.next(); IMEMonitorHandlerReceiver receiver = e.getKey(); - if ( receiver.isValid( e.getValue() ) ) + if( receiver.isValid( e.getValue() ) ) receiver.onListUpdate(); else i.remove(); diff --git a/src/main/java/appeng/me/storage/MEPassThrough.java b/src/main/java/appeng/me/storage/MEPassThrough.java index 2dd68f3b6..2eeb68134 100644 --- a/src/main/java/appeng/me/storage/MEPassThrough.java +++ b/src/main/java/appeng/me/storage/MEPassThrough.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -27,41 +28,43 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; + public class MEPassThrough> implements IMEInventoryHandler { - private IMEInventory internal; final protected StorageChannel channel; + private IMEInventory internal; + + public MEPassThrough( IMEInventory i, StorageChannel channel ) + { + this.channel = channel; + this.setInternal( i ); + } protected IMEInventory getInternal() { return this.internal; } - public MEPassThrough(IMEInventory i, StorageChannel channel) { - this.channel = channel; - this.setInternal( i ); - } - - public void setInternal(IMEInventory i) + public void setInternal( IMEInventory i ) { this.internal = i; } @Override - public T injectItems(T input, Actionable type, BaseActionSource src) + public T injectItems( T input, Actionable type, BaseActionSource src ) { return this.internal.injectItems( input, type, src ); } @Override - public T extractItems(T request, Actionable type, BaseActionSource src) + public T extractItems( T request, Actionable type, BaseActionSource src ) { return this.internal.extractItems( request, type, src ); } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { return this.internal.getAvailableItems( out ); } @@ -79,13 +82,13 @@ public class MEPassThrough> implements IMEInventoryHandler } @Override - public boolean isPrioritized(T input) + public boolean isPrioritized( T input ) { return false; } @Override - public boolean canAccept(T input) + public boolean canAccept( T input ) { return true; } @@ -103,9 +106,8 @@ public class MEPassThrough> implements IMEInventoryHandler } @Override - public boolean validForPass(int i) + public boolean validForPass( int i ) { return true; } - } diff --git a/src/main/java/appeng/me/storage/NetworkInventoryHandler.java b/src/main/java/appeng/me/storage/NetworkInventoryHandler.java index 90bfdcf03..1db1ddae6 100644 --- a/src/main/java/appeng/me/storage/NetworkInventoryHandler.java +++ b/src/main/java/appeng/me/storage/NetworkInventoryHandler.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; @@ -42,157 +43,75 @@ import appeng.api.storage.data.IItemList; import appeng.me.cache.SecurityCache; import appeng.util.ItemSorters; + public class NetworkInventoryHandler> implements IMEInventoryHandler { - private final static Comparator PRIORITY_SORTER = new Comparator() { + static final ThreadLocal DEPTH_MOD = new ThreadLocal(); + static final ThreadLocal DEPTH_SIM = new ThreadLocal(); + private final static Comparator PRIORITY_SORTER = new Comparator() + { @Override - public int compare(Integer o1, Integer o2) + public int compare( Integer o1, Integer o2 ) { return ItemSorters.compareInt( o2, o1 ); } - }; - + static int currentPass = 0; final StorageChannel myChannel; final SecurityCache security; - // final TreeMultimap> priorityInventory; private final NavigableMap>> priorityInventory; + int myPass = 0; - public NetworkInventoryHandler(StorageChannel chan, SecurityCache security) { + public NetworkInventoryHandler( StorageChannel chan, SecurityCache security ) + { this.myChannel = chan; this.security = security; this.priorityInventory = new TreeMap>>( PRIORITY_SORTER ); // TreeMultimap.create( prioritySorter, hashSorter ); } - public void addNewStorage(IMEInventoryHandler h) + public void addNewStorage( IMEInventoryHandler h ) { int priority = h.getPriority(); List> list = this.priorityInventory.get( priority ); - if ( list == null ) + if( list == null ) this.priorityInventory.put( priority, list = new ArrayList>() ); list.add( h ); } - static int currentPass = 0; - int myPass = 0; - static final ThreadLocal DEPTH_MOD = new ThreadLocal(); - static final ThreadLocal DEPTH_SIM = new ThreadLocal(); - - private LinkedList getDepth(Actionable type) - { - ThreadLocal depth = type == Actionable.MODULATE ? DEPTH_MOD : DEPTH_SIM; - - LinkedList s = depth.get(); - - if ( s == null ) - depth.set( s = new LinkedList() ); - - return s; - } - - private boolean diveList(NetworkInventoryHandler networkInventoryHandler, Actionable type) - { - LinkedList cDepth = this.getDepth( type ); - if ( cDepth.contains( networkInventoryHandler ) ) - return true; - - cDepth.push( this ); - return false; - } - - private boolean diveIteration(NetworkInventoryHandler networkInventoryHandler, Actionable type) - { - LinkedList cDepth = this.getDepth( type ); - if ( cDepth.isEmpty() ) - { - currentPass++; - this.myPass = currentPass; - } - else - { - if ( currentPass == this.myPass ) - return true; - else - this.myPass = currentPass; - } - - cDepth.push( this ); - return false; - } - - private void surface(NetworkInventoryHandler networkInventoryHandler, Actionable type) - { - if ( this.getDepth( type ).pop() != this ) - throw new RuntimeException( "Invalid Access to Networked Storage API detected." ); - } - - private boolean testPermission(BaseActionSource src, SecurityPermissions permission) - { - if ( src.isPlayer() ) - { - if ( !this.security.hasPermission( ((PlayerSource) src).player, permission ) ) - return true; - } - else if ( src.isMachine() ) - { - if ( this.security.isAvailable() ) - { - IGridNode n = ((MachineSource) src).via.getActionableNode(); - if ( n == null ) - return true; - - IGrid gn = n.getGrid(); - if ( gn != this.security.myGrid ) - { - int playerID = -1; - - ISecurityGrid sg = gn.getCache( ISecurityGrid.class ); - playerID = sg.getOwner(); - - if ( !this.security.hasPermission( playerID, permission ) ) - return true; - } - } - } - - return false; - } - @Override - public T injectItems(T input, Actionable type, BaseActionSource src) + public T injectItems( T input, Actionable type, BaseActionSource src ) { - if ( this.diveList( this, type ) ) + if( this.diveList( this, type ) ) return input; - if ( this.testPermission( src, SecurityPermissions.INJECT ) ) + if( this.testPermission( src, SecurityPermissions.INJECT ) ) { this.surface( this, type ); return input; } - for (List> invList : this.priorityInventory.values()) + for( List> invList : this.priorityInventory.values() ) { Iterator> ii = invList.iterator(); - while (ii.hasNext() && input != null) + while( ii.hasNext() && input != null ) { IMEInventoryHandler inv = ii.next(); - if ( inv.validForPass( 1 ) && inv.canAccept( input ) - && (inv.isPrioritized( input ) || inv.extractItems( input, Actionable.SIMULATE, src ) != null) ) + if( inv.validForPass( 1 ) && inv.canAccept( input ) && ( inv.isPrioritized( input ) || inv.extractItems( input, Actionable.SIMULATE, src ) != null ) ) { input = inv.injectItems( input, type, src ); } } ii = invList.iterator(); - while (ii.hasNext() && input != null) + while( ii.hasNext() && input != null ) { IMEInventoryHandler inv = ii.next(); - if ( inv.validForPass( 2 ) && inv.canAccept( input ) )// ignore crafting on the second pass. + if( inv.validForPass( 2 ) && inv.canAccept( input ) )// ignore crafting on the second pass. { input = inv.injectItems( input, type, src ); } @@ -204,13 +123,73 @@ public class NetworkInventoryHandler> implements IMEInvent return input; } - @Override - public T extractItems(T request, Actionable mode, BaseActionSource src) + private boolean diveList( NetworkInventoryHandler networkInventoryHandler, Actionable type ) { - if ( this.diveList( this, mode ) ) + LinkedList cDepth = this.getDepth( type ); + if( cDepth.contains( networkInventoryHandler ) ) + return true; + + cDepth.push( this ); + return false; + } + + private boolean testPermission( BaseActionSource src, SecurityPermissions permission ) + { + if( src.isPlayer() ) + { + if( !this.security.hasPermission( ( (PlayerSource) src ).player, permission ) ) + return true; + } + else if( src.isMachine() ) + { + if( this.security.isAvailable() ) + { + IGridNode n = ( (MachineSource) src ).via.getActionableNode(); + if( n == null ) + return true; + + IGrid gn = n.getGrid(); + if( gn != this.security.myGrid ) + { + int playerID = -1; + + ISecurityGrid sg = gn.getCache( ISecurityGrid.class ); + playerID = sg.getOwner(); + + if( !this.security.hasPermission( playerID, permission ) ) + return true; + } + } + } + + return false; + } + + private void surface( NetworkInventoryHandler networkInventoryHandler, Actionable type ) + { + if( this.getDepth( type ).pop() != this ) + throw new RuntimeException( "Invalid Access to Networked Storage API detected." ); + } + + private LinkedList getDepth( Actionable type ) + { + ThreadLocal depth = type == Actionable.MODULATE ? DEPTH_MOD : DEPTH_SIM; + + LinkedList s = depth.get(); + + if( s == null ) + depth.set( s = new LinkedList() ); + + return s; + } + + @Override + public T extractItems( T request, Actionable mode, BaseActionSource src ) + { + if( this.diveList( this, mode ) ) return null; - if ( this.testPermission( src, SecurityPermissions.EXTRACT ) ) + if( this.testPermission( src, SecurityPermissions.EXTRACT ) ) { this.surface( this, mode ); return null; @@ -223,12 +202,12 @@ public class NetworkInventoryHandler> implements IMEInvent output.setStackSize( 0 ); long req = request.getStackSize(); - while (i.hasNext()) + while( i.hasNext() ) { List> invList = i.next(); Iterator> ii = invList.iterator(); - while (ii.hasNext() && output.getStackSize() < req) + while( ii.hasNext() && output.getStackSize() < req ) { IMEInventoryHandler inv = ii.next(); @@ -239,21 +218,21 @@ public class NetworkInventoryHandler> implements IMEInvent this.surface( this, mode ); - if ( output.getStackSize() <= 0 ) + if( output.getStackSize() <= 0 ) return null; return output; } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { - if ( this.diveIteration( this, Actionable.SIMULATE ) ) + if( this.diveIteration( this, Actionable.SIMULATE ) ) return out; // for (Entry> h : priorityInventory.entries()) - for (List> i : this.priorityInventory.values()) - for (IMEInventoryHandler j : i) + for( List> i : this.priorityInventory.values() ) + for( IMEInventoryHandler j : i ) out = j.getAvailableItems( out ); this.surface( this, Actionable.SIMULATE ); @@ -261,6 +240,26 @@ public class NetworkInventoryHandler> implements IMEInvent return out; } + private boolean diveIteration( NetworkInventoryHandler networkInventoryHandler, Actionable type ) + { + LinkedList cDepth = this.getDepth( type ); + if( cDepth.isEmpty() ) + { + currentPass++; + this.myPass = currentPass; + } + else + { + if( currentPass == this.myPass ) + return true; + else + this.myPass = currentPass; + } + + cDepth.push( this ); + return false; + } + @Override public StorageChannel getChannel() { @@ -274,13 +273,13 @@ public class NetworkInventoryHandler> implements IMEInvent } @Override - public boolean isPrioritized(T input) + public boolean isPrioritized( T input ) { return false; } @Override - public boolean canAccept(T input) + public boolean canAccept( T input ) { return true; } @@ -298,9 +297,8 @@ public class NetworkInventoryHandler> implements IMEInvent } @Override - public boolean validForPass(int i) + public boolean validForPass( int i ) { return true; } - } diff --git a/src/main/java/appeng/me/storage/NullInventory.java b/src/main/java/appeng/me/storage/NullInventory.java index 584bf2763..833bba4f4 100644 --- a/src/main/java/appeng/me/storage/NullInventory.java +++ b/src/main/java/appeng/me/storage/NullInventory.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -26,33 +27,34 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; + public class NullInventory> implements IMEInventoryHandler { @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public T injectItems(T input, Actionable mode, BaseActionSource src) + public T injectItems( T input, Actionable mode, BaseActionSource src ) { return input; } @Override - public T extractItems(T request, Actionable mode, BaseActionSource src) + public T extractItems( T request, Actionable mode, BaseActionSource src ) { return null; } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { return out; } + @Override + public StorageChannel getChannel() + { + return StorageChannel.ITEMS; + } + @Override public AccessRestriction getAccess() { @@ -60,13 +62,13 @@ public class NullInventory> implements IMEInventoryHandler } @Override - public boolean isPrioritized(T input) + public boolean isPrioritized( T input ) { return false; } @Override - public boolean canAccept(T input) + public boolean canAccept( T input ) { return false; } @@ -84,9 +86,8 @@ public class NullInventory> implements IMEInventoryHandler } @Override - public boolean validForPass(int i) + public boolean validForPass( int i ) { return i == 2; } - } diff --git a/src/main/java/appeng/me/storage/SecurityInventory.java b/src/main/java/appeng/me/storage/SecurityInventory.java index 2357ff36d..9d0727752 100644 --- a/src/main/java/appeng/me/storage/SecurityInventory.java +++ b/src/main/java/appeng/me/storage/SecurityInventory.java @@ -18,6 +18,7 @@ package appeng.me.storage; + import com.mojang.authlib.GameProfile; import appeng.api.AEApi; @@ -34,42 +35,28 @@ import appeng.api.storage.data.IItemList; import appeng.me.GridAccessException; import appeng.tile.misc.TileSecurity; + public class SecurityInventory implements IMEInventoryHandler { - final TileSecurity securityTile; final public IItemList storedItems = AEApi.instance().storage().createItemList(); + final TileSecurity securityTile; - public SecurityInventory(TileSecurity ts) { + public SecurityInventory( TileSecurity ts ) + { this.securityTile = ts; } - private boolean hasPermission(BaseActionSource src) - { - if ( src.isPlayer() ) - { - try - { - return this.securityTile.getProxy().getSecurity().hasPermission( ((PlayerSource) src).player, SecurityPermissions.SECURITY ); - } - catch (GridAccessException e) - { - // :P - } - } - return false; - } - @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable type, BaseActionSource src) + public IAEItemStack injectItems( IAEItemStack input, Actionable type, BaseActionSource src ) { - if ( this.hasPermission( src ) ) + if( this.hasPermission( src ) ) { - if ( AEApi.instance().definitions().items().biometricCard().isSameAs( input.getItemStack() ) ) + if( AEApi.instance().definitions().items().biometricCard().isSameAs( input.getItemStack() ) ) { - if ( this.canAccept( input ) ) + if( this.canAccept( input ) ) { - if ( type == Actionable.SIMULATE ) + if( type == Actionable.SIMULATE ) return null; this.storedItems.add( input ); @@ -81,17 +68,33 @@ public class SecurityInventory implements IMEInventoryHandler return input; } - @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) + private boolean hasPermission( BaseActionSource src ) { - if ( this.hasPermission( src ) ) + if( src.isPlayer() ) + { + try + { + return this.securityTile.getProxy().getSecurity().hasPermission( ( (PlayerSource) src ).player, SecurityPermissions.SECURITY ); + } + catch( GridAccessException e ) + { + // :P + } + } + return false; + } + + @Override + public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) + { + if( this.hasPermission( src ) ) { IAEItemStack target = this.storedItems.findPrecise( request ); - if ( target != null ) + if( target != null ) { IAEItemStack output = target.copy(); - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) return output; target.setStackSize( 0 ); @@ -103,9 +106,9 @@ public class SecurityInventory implements IMEInventoryHandler } @Override - public IItemList getAvailableItems(IItemList out) + public IItemList getAvailableItems( IItemList out ) { - for (IAEItemStack ais : this.storedItems) + for( IAEItemStack ais : this.storedItems ) out.add( ais ); return out; @@ -124,32 +127,32 @@ public class SecurityInventory implements IMEInventoryHandler } @Override - public boolean isPrioritized(IAEItemStack input) + public boolean isPrioritized( IAEItemStack input ) { return false; } @Override - public boolean canAccept(IAEItemStack input) + public boolean canAccept( IAEItemStack input ) { - if ( input.getItem() instanceof IBiometricCard ) + if( input.getItem() instanceof IBiometricCard ) { IBiometricCard tbc = (IBiometricCard) input.getItem(); GameProfile newUser = tbc.getProfile( input.getItemStack() ); int PlayerID = AEApi.instance().registries().players().getID( newUser ); - if ( this.securityTile.getOwner() == PlayerID ) + if( this.securityTile.getOwner() == PlayerID ) return false; - for (IAEItemStack ais : this.storedItems) + for( IAEItemStack ais : this.storedItems ) { - if ( ais.isMeaningful() ) + if( ais.isMeaningful() ) { GameProfile thisUser = tbc.getProfile( ais.getItemStack() ); - if ( thisUser == newUser ) + if( thisUser == newUser ) return false; - if ( thisUser != null && thisUser.equals( newUser ) ) + if( thisUser != null && thisUser.equals( newUser ) ) return false; } } @@ -172,9 +175,8 @@ public class SecurityInventory implements IMEInventoryHandler } @Override - public boolean validForPass(int i) + public boolean validForPass( int i ) { return true; } - } diff --git a/src/main/java/appeng/me/storage/VoidFluidInventory.java b/src/main/java/appeng/me/storage/VoidFluidInventory.java index f951a1754..f767f01a4 100644 --- a/src/main/java/appeng/me/storage/VoidFluidInventory.java +++ b/src/main/java/appeng/me/storage/VoidFluidInventory.java @@ -42,20 +42,14 @@ public class VoidFluidInventory implements IMEInventoryHandler @Override public IAEFluidStack injectItems( IAEFluidStack input, Actionable mode, BaseActionSource src ) { - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) return null; - if ( input != null ) + if( input != null ) this.target.addPower( input.getStackSize() / 1000.0 ); return null; } - @Override - public StorageChannel getChannel() - { - return StorageChannel.FLUIDS; - } - @Override public IAEFluidStack extractItems( IAEFluidStack request, Actionable mode, BaseActionSource src ) { @@ -68,6 +62,12 @@ public class VoidFluidInventory implements IMEInventoryHandler return out; } + @Override + public StorageChannel getChannel() + { + return StorageChannel.FLUIDS; + } + @Override public AccessRestriction getAccess() { @@ -103,5 +103,4 @@ public class VoidFluidInventory implements IMEInventoryHandler { return i == 2; } - } diff --git a/src/main/java/appeng/me/storage/VoidItemInventory.java b/src/main/java/appeng/me/storage/VoidItemInventory.java index c2e796f30..ad8272107 100644 --- a/src/main/java/appeng/me/storage/VoidItemInventory.java +++ b/src/main/java/appeng/me/storage/VoidItemInventory.java @@ -42,20 +42,14 @@ public class VoidItemInventory implements IMEInventoryHandler @Override public IAEItemStack injectItems( IAEItemStack input, Actionable mode, BaseActionSource src ) { - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) return null; - if ( input != null ) + if( input != null ) this.target.addPower( input.getStackSize() ); return null; } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - @Override public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) { @@ -68,6 +62,12 @@ public class VoidItemInventory implements IMEInventoryHandler return out; } + @Override + public StorageChannel getChannel() + { + return StorageChannel.ITEMS; + } + @Override public AccessRestriction getAccess() { @@ -103,5 +103,4 @@ public class VoidItemInventory implements IMEInventoryHandler { return i == 2; } - } diff --git a/src/main/java/appeng/parts/AEBasePart.java b/src/main/java/appeng/parts/AEBasePart.java index 72d927eec..e77133796 100644 --- a/src/main/java/appeng/parts/AEBasePart.java +++ b/src/main/java/appeng/parts/AEBasePart.java @@ -18,6 +18,7 @@ package appeng.parts; + import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; @@ -71,27 +72,74 @@ import appeng.tile.inventory.AppEngInternalAEInventory; import appeng.util.Platform; import appeng.util.SettingsFrom; + public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, IUpgradeableHost, ICustomNameObject { - protected ISimplifiedBundle renderCache = null; - protected final AENetworkProxy proxy; + protected final ItemStack is; + protected ISimplifiedBundle renderCache = null; protected TileEntity tile = null; protected IPartHost host = null; protected ForgeDirection side = null; - protected final ItemStack is; - - public AEBasePart(ItemStack is) { + public AEBasePart( ItemStack is ) + { this.is = is; this.proxy = new AENetworkProxy( this, "part", is, this instanceof PartCable ); this.proxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); } + public IPartHost getHost() + { + return this.host; + } + @Override - @SideOnly(Side.CLIENT) - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) + public IGridNode getGridNode( ForgeDirection dir ) + { + return this.proxy.getNode(); + } + + @Override + public AECableType getCableConnectionType( ForgeDirection dir ) + { + return AECableType.GLASS; + } + + @Override + public void securityBreak() + { + if( this.is.stackSize > 0 ) + { + List items = new ArrayList(); + items.add( this.is.copy() ); + this.host.removePart( this.side, false ); + Platform.spawnDrops( this.tile.getWorldObj(), this.tile.xCoord, this.tile.yCoord, this.tile.zCoord, items ); + this.is.stackSize = 0; + } + } + + protected AEColor getColor() + { + if( this.host == null ) + return AEColor.Transparent; + return this.host.getColor(); + } + + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + + } + + @Override + public int getInstalledUpgrades( Upgrades u ) + { + return 0; + } @Override + @SideOnly( Side.CLIENT ) + public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) { rh.setBounds( 1, 1, 1, 15, 15, 15 ); rh.renderInventoryBox( renderer ); @@ -101,24 +149,78 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - @SideOnly(Side.CLIENT) - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) + public TileEntity getTile() + { + return this.tile; + } + + @Override + public AENetworkProxy getProxy() + { + return this.proxy; + } + + @Override + public DimensionalCoord getLocation() + { + return new DimensionalCoord( this.tile ); + } + + @Override + public void gridChanged() + { + + } + + @Override + public IGridNode getActionableNode() + { + return this.proxy.getNode(); + } + + public void saveChanges() + { + this.host.markForSave(); + } + + @Override + public String getCustomName() + { + return this.is.getDisplayName(); + } @Override + @SideOnly( Side.CLIENT ) + public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) { rh.setBounds( 1, 1, 1, 15, 15, 15 ); rh.renderBlock( x, y, z, renderer ); } @Override - @SideOnly(Side.CLIENT) - public void renderDynamic(double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer) + public boolean hasCustomName() + { + return this.is.hasDisplayName(); + } + + public void addEntityCrashInfo( CrashReportCategory crashreportcategory ) + { + crashreportcategory.addCrashSection( "Part Side", this.side ); + } + + + + + + @Override + @SideOnly( Side.CLIENT ) + public void renderDynamic( double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer ) { } @Override - public ItemStack getItemStack(PartItemStack type) + public ItemStack getItemStack( PartItemStack type ) { - if ( type == PartItemStack.Network ) + if( type == PartItemStack.Network ) { ItemStack copy = this.is.copy(); copy.setTagCompound( null ); @@ -146,13 +248,13 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public void readFromNBT(NBTTagCompound data) + public void readFromNBT( NBTTagCompound data ) { this.proxy.readFromNBT( data ); } @Override - public void writeToNBT(NBTTagCompound data) + public void writeToNBT( NBTTagCompound data ) { this.proxy.writeToNBT( data ); } @@ -170,13 +272,13 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public void writeToStream(ByteBuf data) throws IOException + public void writeToStream( ByteBuf data ) throws IOException { } @Override - public boolean readFromStream(ByteBuf data) throws IOException + public boolean readFromStream( ByteBuf data ) throws IOException { return false; } @@ -188,7 +290,7 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public void onEntityCollision(Entity entity) + public void onEntityCollision( Entity entity ) { } @@ -206,18 +308,13 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public void setPartHostInfo(ForgeDirection side, IPartHost host, TileEntity tile) + public void setPartHostInfo( ForgeDirection side, IPartHost host, TileEntity tile ) { this.side = side; this.tile = tile; this.host = host; } - public IPartHost getHost() - { - return this.host; - } - @Override public IGridNode getExternalFacingNode() { @@ -225,33 +322,8 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public IGridNode getGridNode(ForgeDirection dir) - { - return this.proxy.getNode(); - } - - protected AEColor getColor() - { - if ( this.host == null ) - return AEColor.Transparent; - return this.host.getColor(); - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this.tile ); - } - - @Override - public void getBoxes(IPartCollisionHelper bch) - { - - } - - @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World world, int x, int y, int z, Random r) + @SideOnly( Side.CLIENT ) + public void randomDisplayTick( World world, int x, int y, int z, Random r ) { } @@ -263,13 +335,7 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public AECableType getCableConnectionType(ForgeDirection dir) - { - return AECableType.GLASS; - } - - @Override - public void getDrops(List drops, boolean wrenched) + public void getDrops( List drops, boolean wrenched ) { } @@ -281,13 +347,7 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public void gridChanged() - { - - } - - @Override - public boolean isLadder(EntityLivingBase entity) + public boolean isLadder( EntityLivingBase entity ) { return false; } @@ -299,45 +359,39 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public IInventory getInventoryByName(String name) + public IInventory getInventoryByName( String name ) { return null; } - @Override - public int getInstalledUpgrades(Upgrades u) - { - return 0; - } - /** * depending on the from, different settings will be accepted, don't call this with null * - * @param from source of settings + * @param from source of settings * @param compound compound of source */ - public void uploadSettings(SettingsFrom from, NBTTagCompound compound) + public void uploadSettings( SettingsFrom from, NBTTagCompound compound ) { - if ( compound != null ) + if( compound != null ) { IConfigManager cm = this.getConfigManager(); - if ( cm != null ) + if( cm != null ) cm.readFromNBT( compound ); } - if ( this instanceof IPriorityHost ) + if( this instanceof IPriorityHost ) { IPriorityHost pHost = (IPriorityHost) this; pHost.setPriority( compound.getInteger( "priority" ) ); } IInventory inv = this.getInventoryByName( "config" ); - if ( inv instanceof AppEngInternalAEInventory ) + if( inv instanceof AppEngInternalAEInventory ) { AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; AppEngInternalAEInventory tmp = new AppEngInternalAEInventory( null, target.getSizeInventory() ); tmp.readFromNBT( compound, "config" ); - for (int x = 0; x < tmp.getSizeInventory(); x++) + for( int x = 0; x < tmp.getSizeInventory(); x++ ) target.setInventorySlotContents( x, tmp.getStackInSlot( x ) ); } } @@ -346,26 +400,27 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, * null means nothing to store... * * @param from source of settings + * * @return compound of source */ - public NBTTagCompound downloadSettings(SettingsFrom from) + public NBTTagCompound downloadSettings( SettingsFrom from ) { NBTTagCompound output = new NBTTagCompound(); IConfigManager cm = this.getConfigManager(); - if ( cm != null ) + if( cm != null ) cm.writeToNBT( output ); - if ( this instanceof IPriorityHost ) + if( this instanceof IPriorityHost ) { IPriorityHost pHost = (IPriorityHost) this; output.setInteger( "priority", pHost.getPriority() ); } IInventory inv = this.getInventoryByName( "config" ); - if ( inv instanceof AppEngInternalAEInventory ) + if( inv instanceof AppEngInternalAEInventory ) { - ((AppEngInternalAEInventory) inv).writeToNBT( output, "config" ); + ( (AppEngInternalAEInventory) inv ).writeToNBT( output, "config" ); } return output.hasNoTags() ? null : output; @@ -376,11 +431,11 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, return true; } - private boolean useMemoryCard(EntityPlayer player) + private boolean useMemoryCard( EntityPlayer player ) { ItemStack memCardIS = player.inventory.getCurrentItem(); - if ( memCardIS != null && this.useStandardMemoryCard() && memCardIS.getItem() instanceof IMemoryCard ) + if( memCardIS != null && this.useStandardMemoryCard() && memCardIS.getItem() instanceof IMemoryCard ) { IMemoryCard memoryCard = (IMemoryCard) memCardIS.getItem(); @@ -388,9 +443,9 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, // Blocks and parts share the same soul! final IDefinitions definitions = AEApi.instance().definitions(); - if ( definitions.parts().iface().isSameAs( is ) ) + if( definitions.parts().iface().isSameAs( is ) ) { - for ( ItemStack iface : definitions.blocks().iface().maybeStack( 1 ).asSet() ) + for( ItemStack iface : definitions.blocks().iface().maybeStack( 1 ).asSet() ) { is = iface; } @@ -398,10 +453,10 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, String name = is.getUnlocalizedName(); - if ( player.isSneaking() ) + if( player.isSneaking() ) { NBTTagCompound data = this.downloadSettings( SettingsFrom.MEMORY_CARD ); - if ( data != null ) + if( data != null ) { memoryCard.setMemoryCardContents( memCardIS, name, data ); memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); @@ -411,7 +466,7 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, { String storedName = memoryCard.getSettingsName( memCardIS ); NBTTagCompound data = memoryCard.getData( memCardIS ); - if ( name.equals( storedName ) ) + if( name.equals( storedName ) ) { this.uploadSettings( SettingsFrom.MEMORY_CARD, data ); memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); @@ -425,81 +480,45 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - final public boolean onActivate(EntityPlayer player, Vec3 pos) + final public boolean onActivate( EntityPlayer player, Vec3 pos ) { - if ( this.useMemoryCard( player ) ) + if( this.useMemoryCard( player ) ) return true; return this.onPartActivate( player, pos ); } @Override - final public boolean onShiftActivate(EntityPlayer player, Vec3 pos) + final public boolean onShiftActivate( EntityPlayer player, Vec3 pos ) { - if ( this.useMemoryCard( player ) ) + if( this.useMemoryCard( player ) ) return true; return this.onPartShiftActivate( player, pos ); } - public boolean onPartActivate(EntityPlayer player, Vec3 pos) + public boolean onPartActivate( EntityPlayer player, Vec3 pos ) { return false; } - public boolean onPartShiftActivate(EntityPlayer player, Vec3 pos) + public boolean onPartShiftActivate( EntityPlayer player, Vec3 pos ) { return false; } @Override - public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) + public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) { this.proxy.setOwner( player ); } @Override - public TileEntity getTile() - { - return this.tile; - } - - @Override - public void securityBreak() - { - if ( this.is.stackSize > 0 ) - { - List items = new ArrayList(); - items.add( this.is.copy() ); - this.host.removePart( this.side, false ); - Platform.spawnDrops( this.tile.getWorldObj(), this.tile.xCoord, this.tile.yCoord, this.tile.zCoord, items ); - this.is.stackSize = 0; - } - } - - @Override - public AENetworkProxy getProxy() - { - return this.proxy; - } - - @Override - public IGridNode getActionableNode() - { - return this.proxy.getNode(); - } - - @Override - public boolean canBePlacedOn(BusSupport what) + public boolean canBePlacedOn( BusSupport what ) { return what == BusSupport.CABLE; } - public void saveChanges() - { - this.host.markForSave(); - } - @Override public boolean requireDynamicRender() { @@ -507,26 +526,9 @@ public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, } @Override - public String getCustomName() - { - return this.is.getDisplayName(); - } - - @Override - public boolean hasCustomName() - { - return this.is.hasDisplayName(); - } - - @Override - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public IIcon getBreakingTexture() { return null; } - - public void addEntityCrashInfo(CrashReportCategory crashreportcategory) - { - crashreportcategory.addCrashSection( "Part Side", this.side ); - } } \ No newline at end of file diff --git a/src/main/java/appeng/parts/BusCollisionHelper.java b/src/main/java/appeng/parts/BusCollisionHelper.java index 115f0cbd9..0e5f75e15 100644 --- a/src/main/java/appeng/parts/BusCollisionHelper.java +++ b/src/main/java/appeng/parts/BusCollisionHelper.java @@ -18,6 +18,7 @@ package appeng.parts; + import java.util.List; import net.minecraft.entity.Entity; @@ -26,6 +27,7 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.parts.IPartCollisionHelper; + public class BusCollisionHelper implements IPartCollisionHelper { @@ -38,7 +40,8 @@ public class BusCollisionHelper implements IPartCollisionHelper final private Entity entity; final private boolean isVisual; - public BusCollisionHelper(List boxes, ForgeDirection x, ForgeDirection y, ForgeDirection z, Entity e, boolean visual) { + public BusCollisionHelper( List boxes, ForgeDirection x, ForgeDirection y, ForgeDirection z, Entity e, boolean visual ) + { this.boxes = boxes; this.x = x; this.y = y; @@ -47,58 +50,53 @@ public class BusCollisionHelper implements IPartCollisionHelper this.isVisual = visual; } - public BusCollisionHelper(List boxes, ForgeDirection s, Entity e, boolean visual) { + public BusCollisionHelper( List boxes, ForgeDirection s, Entity e, boolean visual ) + { this.boxes = boxes; this.entity = e; this.isVisual = visual; - switch (s) + switch( s ) { - case DOWN: - this.x = ForgeDirection.EAST; - this.y = ForgeDirection.NORTH; - this.z = ForgeDirection.DOWN; - break; - case UP: - this.x = ForgeDirection.EAST; - this.y = ForgeDirection.SOUTH; - this.z = ForgeDirection.UP; - break; - case EAST: - this.x = ForgeDirection.SOUTH; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.EAST; - break; - case WEST: - this.x = ForgeDirection.NORTH; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.WEST; - break; - case NORTH: - this.x = ForgeDirection.WEST; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.NORTH; - break; - case SOUTH: - this.x = ForgeDirection.EAST; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.SOUTH; - break; - case UNKNOWN: - default: - this.x = ForgeDirection.EAST; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.SOUTH; - break; + case DOWN: + this.x = ForgeDirection.EAST; + this.y = ForgeDirection.NORTH; + this.z = ForgeDirection.DOWN; + break; + case UP: + this.x = ForgeDirection.EAST; + this.y = ForgeDirection.SOUTH; + this.z = ForgeDirection.UP; + break; + case EAST: + this.x = ForgeDirection.SOUTH; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.EAST; + break; + case WEST: + this.x = ForgeDirection.NORTH; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.WEST; + break; + case NORTH: + this.x = ForgeDirection.WEST; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.NORTH; + break; + case SOUTH: + this.x = ForgeDirection.EAST; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.SOUTH; + break; + case UNKNOWN: + default: + this.x = ForgeDirection.EAST; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.SOUTH; + break; } } - @Override - public boolean isBBCollision() - { - return !this.isVisual; - } - /** * pretty much useless... */ @@ -108,7 +106,7 @@ public class BusCollisionHelper implements IPartCollisionHelper } @Override - public void addBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) + public void addBox( double minX, double minY, double minZ, double maxX, double maxY, double maxZ ) { minX /= 16.0; minY /= 16.0; @@ -125,19 +123,19 @@ public class BusCollisionHelper implements IPartCollisionHelper double bY = maxX * this.x.offsetY + maxY * this.y.offsetY + maxZ * this.z.offsetY; double bZ = maxX * this.x.offsetZ + maxY * this.y.offsetZ + maxZ * this.z.offsetZ; - if ( this.x.offsetX + this.y.offsetX + this.z.offsetX < 0 ) + if( this.x.offsetX + this.y.offsetX + this.z.offsetX < 0 ) { aX += 1; bX += 1; } - if ( this.x.offsetY + this.y.offsetY + this.z.offsetY < 0 ) + if( this.x.offsetY + this.y.offsetY + this.z.offsetY < 0 ) { aY += 1; bY += 1; } - if ( this.x.offsetZ + this.y.offsetZ + this.z.offsetZ < 0 ) + if( this.x.offsetZ + this.y.offsetZ + this.z.offsetZ < 0 ) { aZ += 1; bZ += 1; @@ -171,4 +169,9 @@ public class BusCollisionHelper implements IPartCollisionHelper return this.z; } + @Override + public boolean isBBCollision() + { + return !this.isVisual; + } } diff --git a/src/main/java/appeng/parts/CableBusContainer.java b/src/main/java/appeng/parts/CableBusContainer.java index 386288568..6d6cdf1f9 100644 --- a/src/main/java/appeng/parts/CableBusContainer.java +++ b/src/main/java/appeng/parts/CableBusContainer.java @@ -18,6 +18,7 @@ package appeng.parts; + import java.io.IOException; import java.util.EnumSet; import java.util.LinkedList; @@ -70,41 +71,34 @@ import appeng.integration.abstraction.ICLApi; import appeng.me.GridConnection; import appeng.util.Platform; + public class CableBusContainer extends CableBusStorage implements AEMultiTile, ICableBusContainer { + private static final ThreadLocal IS_LOADING = new ThreadLocal(); private final EnumSet myLayerFlags = EnumSet.noneOf( LayerFlags.class ); - public YesNo hasRedstone = YesNo.UNDECIDED; public IPartHost tcb; - - boolean inWorld = false; public boolean requiresDynamicRender = false; + boolean inWorld = false; - @Override - public boolean isInWorld() + public CableBusContainer( IPartHost host ) { - return this.inWorld; + this.tcb = host; } - public void setHost(IPartHost host) + public static boolean isLoading() + { + Boolean is = IS_LOADING.get(); + return is != null && is; + } + + public void setHost( IPartHost host ) { this.tcb.clearContainer(); this.tcb = host; } - public CableBusContainer(IPartHost host) { - this.tcb = host; - } - - @Override - public IPart getPart(ForgeDirection side) - { - if ( side == ForgeDirection.UNKNOWN ) - return this.getCenter(); - return this.getSide( side ); - } - public void rotateLeft() { IPart[] newSides = new IPart[6]; @@ -117,78 +111,25 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I newSides[ForgeDirection.WEST.ordinal()] = this.getSide( ForgeDirection.SOUTH ); newSides[ForgeDirection.NORTH.ordinal()] = this.getSide( ForgeDirection.WEST ); - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) this.setSide( dir, newSides[dir.ordinal()] ); this.getFacadeContainer().rotateLeft(); } - public void updateDynamicRender() + @Override + public IFacadeContainer getFacadeContainer() { - this.requiresDynamicRender = false; - for (ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) - { - IPart p = this.getPart( s ); - if ( p != null ) - this.requiresDynamicRender = this.requiresDynamicRender || p.requireDynamicRender(); - } + return new FacadeContainer( this ); } @Override - public void removePart(ForgeDirection side, boolean suppressUpdate) + public boolean canAddPart( ItemStack is, ForgeDirection side ) { - if ( side == ForgeDirection.UNKNOWN ) - { - if ( this.getCenter() != null ) - this.getCenter().removeFromWorld(); - this.setCenter( null ); - } - else - { - if ( this.getSide( side ) != null ) - this.getSide( side ).removeFromWorld(); - this.setSide( side, null ); - } - - if ( !suppressUpdate ) - { - this.updateDynamicRender(); - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - } - } - - /** - * use for FMP - */ - public void updateConnections() - { - if ( this.getCenter() != null ) - { - EnumSet sides = EnumSet.allOf( ForgeDirection.class ); - - for (ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) - { - if ( this.getPart( s ) != null || this.isBlocked( s ) ) - sides.remove( s ); - } - - this.getCenter().setValidSides( sides ); - IGridNode n = this.getCenter().getGridNode(); - if ( n != null ) - n.updateState(); - } - } - - @Override - public boolean canAddPart(ItemStack is, ForgeDirection side) - { - if ( PartPlacement.isFacade( is, side ) != null ) + if( PartPlacement.isFacade( is, side ) != null ) return true; - if ( is.getItem() instanceof IPartItem ) + if( is.getItem() instanceof IPartItem ) { IPartItem bi = (IPartItem) is.getItem(); @@ -196,24 +137,24 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I is.stackSize = 1; IPart bp = bi.createPartFromItemStack( is ); - if ( bp != null ) + if( bp != null ) { - if ( bp instanceof IPartCable ) + if( bp instanceof IPartCable ) { boolean canPlace = true; - for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) - if ( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ((IPartCable) bp).supportsBuses() ) ) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) + if( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ( (IPartCable) bp ).supportsBuses() ) ) canPlace = false; - if ( !canPlace ) + if( !canPlace ) return false; return this.getPart( ForgeDirection.UNKNOWN ) == null; } - else if ( !(bp instanceof IPartCable) && side != ForgeDirection.UNKNOWN ) + else if( !( bp instanceof IPartCable ) && side != ForgeDirection.UNKNOWN ) { IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if ( cable != null && !bp.canBePlacedOn( ((IPartCable) cable).supportsBuses() ) ) + if( cable != null && !bp.canBePlacedOn( ( (IPartCable) cable ).supportsBuses() ) ) return false; return this.getPart( side ) == null; @@ -224,11 +165,11 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I } @Override - public ForgeDirection addPart(ItemStack is, ForgeDirection side, EntityPlayer player) + public ForgeDirection addPart( ItemStack is, ForgeDirection side, EntityPlayer player ) { - if ( this.canAddPart( is, side ) ) + if( this.canAddPart( is, side ) ) { - if ( is.getItem() instanceof IPartItem ) + if( is.getItem() instanceof IPartItem ) { IPartItem bi = (IPartItem) is.getItem(); @@ -236,44 +177,44 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I is.stackSize = 1; IPart bp = bi.createPartFromItemStack( is ); - if ( bp instanceof IPartCable ) + if( bp instanceof IPartCable ) { boolean canPlace = true; - for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) - if ( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ((IPartCable) bp).supportsBuses() ) ) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) + if( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ( (IPartCable) bp ).supportsBuses() ) ) canPlace = false; - if ( !canPlace ) + if( !canPlace ) return null; - if ( this.getPart( ForgeDirection.UNKNOWN ) != null ) + if( this.getPart( ForgeDirection.UNKNOWN ) != null ) return null; this.setCenter( (IPartCable) bp ); bp.setPartHostInfo( ForgeDirection.UNKNOWN, this, this.tcb.getTile() ); - if ( player != null ) + if( player != null ) bp.onPlacement( player, is, side ); - if ( this.inWorld ) + if( this.inWorld ) bp.addToWorld(); IGridNode cn = this.getCenter().getGridNode(); - if ( cn != null ) + if( cn != null ) { - for (ForgeDirection ins : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection ins : ForgeDirection.VALID_DIRECTIONS ) { IPart sbp = this.getPart( ins ); - if ( sbp != null ) + if( sbp != null ) { IGridNode sn = sbp.getGridNode(); - if ( sn != null ) + if( sn != null ) { try { new GridConnection( cn, sn, ForgeDirection.UNKNOWN ); } - catch (FailedConnection e) + catch( FailedConnection e ) { // ekk! @@ -292,33 +233,33 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I this.partChanged(); return ForgeDirection.UNKNOWN; } - else if ( bp != null && !(bp instanceof IPartCable) && side != ForgeDirection.UNKNOWN ) + else if( bp != null && !( bp instanceof IPartCable ) && side != ForgeDirection.UNKNOWN ) { IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if ( cable != null && !bp.canBePlacedOn( ((IPartCable) cable).supportsBuses() ) ) + if( cable != null && !bp.canBePlacedOn( ( (IPartCable) cable ).supportsBuses() ) ) return null; this.setSide( side, bp ); bp.setPartHostInfo( side, this, this.getTile() ); - if ( player != null ) + if( player != null ) bp.onPlacement( player, is, side ); - if ( this.inWorld ) + if( this.inWorld ) bp.addToWorld(); - if ( this.getCenter() != null ) + if( this.getCenter() != null ) { IGridNode cn = this.getCenter().getGridNode(); IGridNode sn = bp.getGridNode(); - if ( cn != null && sn != null ) + if( cn != null && sn != null ) { try { new GridConnection( cn, sn, ForgeDirection.UNKNOWN ); } - catch (FailedConnection e) + catch( FailedConnection e ) { // ekk! @@ -341,439 +282,40 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I return null; } - private static final ThreadLocal IS_LOADING = new ThreadLocal(); - - public static boolean isLoading() + @Override + public IPart getPart( ForgeDirection side ) { - Boolean is = IS_LOADING.get(); - return is != null && is; - } - - public void addToWorld() - { - if ( this.inWorld ) - return; - - this.inWorld = true; - IS_LOADING.set( true ); - - TileEntity te = this.getTile(); - - // start with the center, then install the side parts into the grid. - for (int x = 6; x >= 0; x--) - { - ForgeDirection s = ForgeDirection.getOrientation( x ); - IPart part = this.getPart( s ); - - if ( part != null ) - { - part.setPartHostInfo( s, this, te ); - part.addToWorld(); - - if ( s != ForgeDirection.UNKNOWN ) - { - IGridNode sn = part.getGridNode(); - if ( sn != null ) - { - // this is a really stupid if statement, why was this - // here? - // if ( !sn.getConnections().iterator().hasNext() ) - - IPart center = this.getPart( ForgeDirection.UNKNOWN ); - if ( center != null ) - { - IGridNode cn = center.getGridNode(); - if ( cn != null ) - { - try - { - AEApi.instance().createGridConnection( cn, sn ); - } - catch (FailedConnection e) - { - // ekk - } - } - } - - } - } - } - } - - this.partChanged(); - - IS_LOADING.set( false ); - } - - public void removeFromWorld() - { - if ( !this.inWorld ) - return; - - this.inWorld = false; - - for (ForgeDirection s : ForgeDirection.values()) - { - IPart part = this.getPart( s ); - if ( part != null ) - part.removeFromWorld(); - } - - this.partChanged(); + if( side == ForgeDirection.UNKNOWN ) + return this.getCenter(); + return this.getSide( side ); } @Override - public boolean canConnectRedstone(EnumSet enumSet) + public void removePart( ForgeDirection side, boolean suppressUpdate ) { - for (ForgeDirection dir : enumSet) + if( side == ForgeDirection.UNKNOWN ) { - IPart part = this.getPart( dir ); - if ( part != null && part.canConnectRedstone() ) - return true; + if( this.getCenter() != null ) + this.getCenter().removeFromWorld(); + this.setCenter( null ); } - return false; - } - - @Override - public IGridNode getGridNode(ForgeDirection side) - { - IPart part = this.getPart( side ); - if ( part != null ) - { - IGridNode n = part.getExternalFacingNode(); - if ( n != null ) - return n; - } - - if ( this.getCenter() != null ) - return this.getCenter().getGridNode(); - - return null; - } - - public Iterable getSelectedBoundingBoxesFromPool(boolean ignoreCableConnections, boolean includeFacades, Entity e, boolean visual) - { - List boxes = new LinkedList(); - - IFacadeContainer fc = this.getFacadeContainer(); - for (ForgeDirection s : ForgeDirection.values()) - { - IPartCollisionHelper bch = new BusCollisionHelper( boxes, s, e, visual ); - - IPart part = this.getPart( s ); - if ( part != null ) - { - if ( ignoreCableConnections && part instanceof IPartCable ) - bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); - else - part.getBoxes( bch ); - } - - if ( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades || !visual ) - { - if ( includeFacades && s != null && s != ForgeDirection.UNKNOWN ) - { - IFacadePart fp = fc.getFacade( s ); - if ( fp != null ) - fp.getBoxes( bch, e ); - } - } - } - - return boxes; - } - - @Override - public void onEntityCollision(Entity entity) - { - for (ForgeDirection s : ForgeDirection.values()) - { - IPart part = this.getPart( s ); - if ( part != null ) - part.onEntityCollision( entity ); - } - } - - @Override - public boolean isEmpty() - { - IFacadeContainer fc = this.getFacadeContainer(); - for (ForgeDirection s : ForgeDirection.values()) - { - IPart part = this.getPart( s ); - if ( part != null ) - return false; - - if ( s != ForgeDirection.UNKNOWN ) - { - IFacadePart fp = fc.getFacade( s ); - if ( fp != null ) - return false; - } - } - return true; - } - - @Override - public void onNeighborChanged() - { - this.hasRedstone = YesNo.UNDECIDED; - - for (ForgeDirection s : ForgeDirection.values()) - { - IPart part = this.getPart( s ); - if ( part != null ) - part.onNeighborChanged(); - } - } - - private void updateRedstone() - { - TileEntity te = this.getTile(); - this.hasRedstone = te.getWorldObj().isBlockIndirectlyGettingPowered( te.xCoord, te.yCoord, te.zCoord ) ? YesNo.YES : YesNo.NO; - } - - @Override - public boolean isSolidOnSide(ForgeDirection side) - { - if ( side == null || side == ForgeDirection.UNKNOWN ) - return false; - - // facades are solid.. - IFacadePart fp = this.getFacadeContainer().getFacade( side ); - if ( fp != null ) - return true; - - // buses can be too. - IPart part = this.getPart( side ); - return part != null && part.isSolid(); - } - - @Override - public int isProvidingWeakPower(ForgeDirection side) - { - IPart part = this.getPart( side ); - return part != null ? part.isProvidingWeakPower() : 0; - } - - @Override - public int isProvidingStrongPower(ForgeDirection side) - { - IPart part = this.getPart( side ); - return part != null ? part.isProvidingStrongPower() : 0; - } - - @SideOnly(Side.CLIENT) - public void renderStatic(double x, double y, double z) - { - CableRenderHelper.getInstance().renderStatic( this, this.getFacadeContainer() ); - } - - @SideOnly(Side.CLIENT) - public void renderDynamic(double x, double y, double z) - { - CableRenderHelper.getInstance().renderDynamic( this, x, y, z ); - } - - public void writeToStream(ByteBuf data) throws IOException - { - int sides = 0; - for (int x = 0; x < 7; x++) - { - IPart p = this.getPart( ForgeDirection.getOrientation( x ) ); - if ( p != null ) - { - sides |= ( 1 << x ); - } - } - - data.writeByte( (byte) sides ); - - for (int x = 0; x < 7; x++) - { - ItemStack is = null; - IPart p = this.getPart( ForgeDirection.getOrientation( x ) ); - if ( p != null ) - { - is = p.getItemStack( PartItemStack.Network ); - - data.writeShort( Item.getIdFromItem( is.getItem() ) ); - data.writeShort( is.getItemDamage() ); - - p.writeToStream( data ); - } - } - - this.getFacadeContainer().writeToStream( data ); - } - - public boolean readFromStream(ByteBuf data) throws IOException - { - byte sides = data.readByte(); - - boolean updateBlock = false; - - for (int x = 0; x < 7; x++) - { - ForgeDirection side = ForgeDirection.getOrientation( x ); - if ( ((sides & (1 << x)) == (1 << x)) ) - { - IPart p = this.getPart( side ); - - short itemID = data.readShort(); - short dmgValue = data.readShort(); - - Item myItem = Item.getItemById( itemID ); - - ItemStack current = p != null ? p.getItemStack( PartItemStack.Network ) : null; - if ( current != null && current.getItem() == myItem && current.getItemDamage() == dmgValue ) - { - if ( p.readFromStream( data ) ) - updateBlock = true; - } - else - { - this.removePart( side, false ); - side = this.addPart( new ItemStack( myItem, 1, dmgValue ), side, null ); - if ( side != null ) - { - p = this.getPart( side ); - p.readFromStream( data ); - } - else - throw new RuntimeException( "Invalid Stream For CableBus Container." ); - } - } - else if ( this.getPart( side ) != null ) - this.removePart( side, false ); - } - - if ( this.getFacadeContainer().readFromStream( data ) ) - return true; - - return updateBlock; - } - - ForgeDirection getSide(IPart part) - { - if ( this.getCenter() == part ) - return ForgeDirection.UNKNOWN; else { - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) - if ( this.getSide( side ) == part ) - { - return side; - } + if( this.getSide( side ) != null ) + this.getSide( side ).removeFromWorld(); + this.setSide( side, null ); } - throw new RuntimeException( "Uhh Bad Part on Side." ); - } - public void writeToNBT(NBTTagCompound data) - { - data.setInteger( "hasRedstone", this.hasRedstone.ordinal() ); - - IFacadeContainer fc = this.getFacadeContainer(); - for (ForgeDirection s : ForgeDirection.values()) + if( !suppressUpdate ) { - fc.writeToNBT( data ); - - IPart part = this.getPart( s ); - if ( part != null ) - { - NBTTagCompound def = new NBTTagCompound(); - part.getItemStack( PartItemStack.World ).writeToNBT( def ); - - NBTTagCompound extra = new NBTTagCompound(); - part.writeToNBT( extra ); - - data.setTag( "def:" + this.getSide( part ).ordinal(), def ); - data.setTag( "extra:" + this.getSide( part ).ordinal(), extra ); - } + this.updateDynamicRender(); + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); } } - public void readFromNBT(NBTTagCompound data) - { - if ( data.hasKey( "hasRedstone" ) ) - this.hasRedstone = YesNo.values()[data.getInteger( "hasRedstone" )]; - - for (int x = 0; x < 7; x++) - { - ForgeDirection side = ForgeDirection.getOrientation( x ); - - NBTTagCompound def = data.getCompoundTag( "def:" + side.ordinal() ); - NBTTagCompound extra = data.getCompoundTag( "extra:" + side.ordinal() ); - if ( def != null && extra != null ) - { - IPart p = this.getPart( side ); - ItemStack iss = ItemStack.loadItemStackFromNBT( def ); - if ( iss == null ) - continue; - - ItemStack current = p == null ? null : p.getItemStack( PartItemStack.World ); - - if ( Platform.isSameItemType( iss, current ) ) - p.readFromNBT( extra ); - else - { - this.removePart( side, true ); - side = this.addPart( iss, side, null ); - if ( side != null ) - { - p = this.getPart( side ); - p.readFromNBT( extra ); - } - else - { - AELog.warning( "Invalid NBT For CableBus Container: " + iss.getItem().getClass().getName() + " is not a valid part; it was ignored." ); - } - } - } - else - this.removePart( side, false ); - } - - this.getFacadeContainer().readFromNBT( data ); - } - - public List getDrops(List drops) - { - for (ForgeDirection s : ForgeDirection.values()) - { - IPart part = this.getPart( s ); - if ( part != null ) - { - drops.add( part.getItemStack( PartItemStack.Break ) ); - part.getDrops( drops, false ); - } - - if ( s != ForgeDirection.UNKNOWN ) - { - IFacadePart fp = this.getFacadeContainer().getFacade( s ); - if ( fp != null ) - drops.add( fp.getItemStack() ); - } - } - - return drops; - } - - public List getNoDrops(List drops) - { - for (ForgeDirection s : ForgeDirection.values()) - { - IPart part = this.getPart( s ); - if ( part != null ) - { - part.getDrops( drops, false ); - } - } - - return drops; - } - @Override public void markForUpdate() { @@ -792,29 +334,10 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I return this.tcb.getTile(); } - @Override - public AECableType getCableConnectionType(ForgeDirection dir) - { - IPart part = this.getPart( dir ); - if ( part instanceof IGridHost ) - { - AECableType t = ((IGridHost) part).getCableConnectionType( dir ); - if ( t != null && t != AECableType.NONE ) - return t; - } - - if ( this.getCenter() != null ) - { - IPartCable c = this.getCenter(); - return c.getCableConnectionType(); - } - return AECableType.NONE; - } - @Override public AEColor getColor() { - if ( this.getCenter() != null ) + if( this.getCenter() != null ) { IPartCable c = this.getCenter(); return c.getCableColor(); @@ -822,12 +345,6 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I return AEColor.Transparent; } - @Override - public IFacadeContainer getFacadeContainer() - { - return new FacadeContainer( this ); - } - @Override public void clearContainer() { @@ -835,68 +352,27 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I } @Override - public boolean isBlocked(ForgeDirection side) + public boolean isBlocked( ForgeDirection side ) { return this.tcb.isBlocked( side ); } @Override - public int getLightValue() + public SelectedPart selectPart( Vec3 pos ) { - int light = 0; - - for (ForgeDirection d : ForgeDirection.values()) - { - IPart p = this.getPart( d ); - if ( p != null ) - light = Math.max( p.getLightLevel(), light ); - } - - if ( light > 0 && AppEng.instance.isIntegrationEnabled( IntegrationType.CLApi ) ) - return ((ICLApi) AppEng.instance.getIntegration( IntegrationType.CLApi )).colorLight( this.getColor(), light ); - - return light; - } - - @Override - public boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who) - { - IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if ( cable != null ) - { - IPartCable pc = (IPartCable) cable; - return pc.changeColor( colour, who ); - } - return false; - } - - @Override - public boolean activate(EntityPlayer player, Vec3 pos) - { - SelectedPart p = this.selectPart( pos ); - if ( p != null && p.part != null ) - { - return p.part.onActivate( player, pos ); - } - return false; - } - - @Override - public SelectedPart selectPart(Vec3 pos) - { - for (ForgeDirection side : ForgeDirection.values()) + for( ForgeDirection side : ForgeDirection.values() ) { IPart p = this.getPart( side ); - if ( p != null ) + if( p != null ) { List boxes = new LinkedList(); IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); p.getBoxes( bch ); - for (AxisAlignedBB bb : boxes) + for( AxisAlignedBB bb : boxes ) { bb = bb.expand( 0.002, 0.002, 0.002 ); - if ( bb.isVecInside( pos ) ) + if( bb.isVecInside( pos ) ) { return new SelectedPart( p, side ); } @@ -904,22 +380,22 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I } } - if ( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades ) + if( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades ) { IFacadeContainer fc = this.getFacadeContainer(); - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) { IFacadePart p = fc.getFacade( side ); - if ( p != null ) + if( p != null ) { List boxes = new LinkedList(); IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); p.getBoxes( bch, null ); - for (AxisAlignedBB bb : boxes) + for( AxisAlignedBB bb : boxes ) { bb = bb.expand( 0.01, 0.01, 0.01 ); - if ( bb.isVecInside( pos ) ) + if( bb.isVecInside( pos ) ) { return new SelectedPart( p, side ); } @@ -931,25 +407,31 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I return new SelectedPart(); } + @Override + public void markForSave() + { + this.tcb.markForSave(); + } + @Override public void partChanged() { - if ( this.getCenter() == null ) + if( this.getCenter() == null ) { List facades = new LinkedList(); IFacadeContainer fc = this.getFacadeContainer(); - for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) { IFacadePart fp = fc.getFacade( d ); - if ( fp != null ) + if( fp != null ) { facades.add( fp.getItemStack() ); fc.removeFacade( this.tcb, d ); } } - if ( !facades.isEmpty() ) + if( !facades.isEmpty() ) { TileEntity te = this.tcb.getTile(); Platform.spawnDrops( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, facades ); @@ -960,58 +442,32 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I } @Override - public void markForSave() + public boolean hasRedstone( ForgeDirection side ) { - this.tcb.markForSave(); - } - - @Override - public void randomDisplayTick(World world, int x, int y, int z, Random r) - { - for (ForgeDirection side : ForgeDirection.values()) - { - IPart p = this.getPart( side ); - if ( p != null ) - { - p.randomDisplayTick( world, x, y, z, r ); - } - } - } - - @Override - public boolean hasRedstone(ForgeDirection side) - { - if ( this.hasRedstone == YesNo.UNDECIDED ) + if( this.hasRedstone == YesNo.UNDECIDED ) this.updateRedstone(); return this.hasRedstone == YesNo.YES; } @Override - public boolean isLadder(EntityLivingBase entity) + public boolean isEmpty() { - for (ForgeDirection side : ForgeDirection.values()) + IFacadeContainer fc = this.getFacadeContainer(); + for( ForgeDirection s : ForgeDirection.values() ) { - IPart p = this.getPart( side ); - if ( p != null ) + IPart part = this.getPart( s ); + if( part != null ) + return false; + + if( s != ForgeDirection.UNKNOWN ) { - if ( p.isLadder( entity ) ) - return true; + IFacadePart fp = fc.getFacade( s ); + if( fp != null ) + return false; } } - - return false; - } - - @Override - public void securityBreak() - { - for (ForgeDirection d : ForgeDirection.values()) - { - IPart p = this.getPart( d ); - if ( p instanceof IGridHost ) - ((IGridHost) p).securityBreak(); - } + return true; } @Override @@ -1032,4 +488,546 @@ public class CableBusContainer extends CableBusStorage implements AEMultiTile, I this.tcb.notifyNeighbors(); } + @Override + public boolean isInWorld() + { + return this.inWorld; + } + + private void updateRedstone() + { + TileEntity te = this.getTile(); + this.hasRedstone = te.getWorldObj().isBlockIndirectlyGettingPowered( te.xCoord, te.yCoord, te.zCoord ) ? YesNo.YES : YesNo.NO; + } + + public void updateDynamicRender() + { + this.requiresDynamicRender = false; + for( ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) + { + IPart p = this.getPart( s ); + if( p != null ) + this.requiresDynamicRender = this.requiresDynamicRender || p.requireDynamicRender(); + } + } + + /** + * use for FMP + */ + public void updateConnections() + { + if( this.getCenter() != null ) + { + EnumSet sides = EnumSet.allOf( ForgeDirection.class ); + + for( ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) + { + if( this.getPart( s ) != null || this.isBlocked( s ) ) + sides.remove( s ); + } + + this.getCenter().setValidSides( sides ); + IGridNode n = this.getCenter().getGridNode(); + if( n != null ) + n.updateState(); + } + } + + public void addToWorld() + { + if( this.inWorld ) + return; + + this.inWorld = true; + IS_LOADING.set( true ); + + TileEntity te = this.getTile(); + + // start with the center, then install the side parts into the grid. + for( int x = 6; x >= 0; x-- ) + { + ForgeDirection s = ForgeDirection.getOrientation( x ); + IPart part = this.getPart( s ); + + if( part != null ) + { + part.setPartHostInfo( s, this, te ); + part.addToWorld(); + + if( s != ForgeDirection.UNKNOWN ) + { + IGridNode sn = part.getGridNode(); + if( sn != null ) + { + // this is a really stupid if statement, why was this + // here? + // if ( !sn.getConnections().iterator().hasNext() ) + + IPart center = this.getPart( ForgeDirection.UNKNOWN ); + if( center != null ) + { + IGridNode cn = center.getGridNode(); + if( cn != null ) + { + try + { + AEApi.instance().createGridConnection( cn, sn ); + } + catch( FailedConnection e ) + { + // ekk + } + } + } + } + } + } + } + + this.partChanged(); + + IS_LOADING.set( false ); + } + + public void removeFromWorld() + { + if( !this.inWorld ) + return; + + this.inWorld = false; + + for( ForgeDirection s : ForgeDirection.values() ) + { + IPart part = this.getPart( s ); + if( part != null ) + part.removeFromWorld(); + } + + this.partChanged(); + } + + @Override + public IGridNode getGridNode( ForgeDirection side ) + { + IPart part = this.getPart( side ); + if( part != null ) + { + IGridNode n = part.getExternalFacingNode(); + if( n != null ) + return n; + } + + if( this.getCenter() != null ) + return this.getCenter().getGridNode(); + + return null; + } + + @Override + public AECableType getCableConnectionType( ForgeDirection dir ) + { + IPart part = this.getPart( dir ); + if( part instanceof IGridHost ) + { + AECableType t = ( (IGridHost) part ).getCableConnectionType( dir ); + if( t != null && t != AECableType.NONE ) + return t; + } + + if( this.getCenter() != null ) + { + IPartCable c = this.getCenter(); + return c.getCableConnectionType(); + } + return AECableType.NONE; + } + + @Override + public void securityBreak() + { + for( ForgeDirection d : ForgeDirection.values() ) + { + IPart p = this.getPart( d ); + if( p instanceof IGridHost ) + ( (IGridHost) p ).securityBreak(); + } + } + + public Iterable getSelectedBoundingBoxesFromPool( boolean ignoreCableConnections, boolean includeFacades, Entity e, boolean visual ) + { + List boxes = new LinkedList(); + + IFacadeContainer fc = this.getFacadeContainer(); + for( ForgeDirection s : ForgeDirection.values() ) + { + IPartCollisionHelper bch = new BusCollisionHelper( boxes, s, e, visual ); + + IPart part = this.getPart( s ); + if( part != null ) + { + if( ignoreCableConnections && part instanceof IPartCable ) + bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); + else + part.getBoxes( bch ); + } + + if( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades || !visual ) + { + if( includeFacades && s != null && s != ForgeDirection.UNKNOWN ) + { + IFacadePart fp = fc.getFacade( s ); + if( fp != null ) + fp.getBoxes( bch, e ); + } + } + } + + return boxes; + } + + @Override + public int isProvidingStrongPower( ForgeDirection side ) + { + IPart part = this.getPart( side ); + return part != null ? part.isProvidingStrongPower() : 0; + } + + @Override + public int isProvidingWeakPower( ForgeDirection side ) + { + IPart part = this.getPart( side ); + return part != null ? part.isProvidingWeakPower() : 0; + } + + @Override + public boolean canConnectRedstone( EnumSet enumSet ) + { + for( ForgeDirection dir : enumSet ) + { + IPart part = this.getPart( dir ); + if( part != null && part.canConnectRedstone() ) + return true; + } + return false; + } + + @Override + public void onEntityCollision( Entity entity ) + { + for( ForgeDirection s : ForgeDirection.values() ) + { + IPart part = this.getPart( s ); + if( part != null ) + part.onEntityCollision( entity ); + } + } + + @Override + public boolean activate( EntityPlayer player, Vec3 pos ) + { + SelectedPart p = this.selectPart( pos ); + if( p != null && p.part != null ) + { + return p.part.onActivate( player, pos ); + } + return false; + } + + @Override + public void onNeighborChanged() + { + this.hasRedstone = YesNo.UNDECIDED; + + for( ForgeDirection s : ForgeDirection.values() ) + { + IPart part = this.getPart( s ); + if( part != null ) + part.onNeighborChanged(); + } + } + + @Override + public boolean isSolidOnSide( ForgeDirection side ) + { + if( side == null || side == ForgeDirection.UNKNOWN ) + return false; + + // facades are solid.. + IFacadePart fp = this.getFacadeContainer().getFacade( side ); + if( fp != null ) + return true; + + // buses can be too. + IPart part = this.getPart( side ); + return part != null && part.isSolid(); + } + + @Override + public boolean isLadder( EntityLivingBase entity ) + { + for( ForgeDirection side : ForgeDirection.values() ) + { + IPart p = this.getPart( side ); + if( p != null ) + { + if( p.isLadder( entity ) ) + return true; + } + } + + return false; + } + + @Override + public void randomDisplayTick( World world, int x, int y, int z, Random r ) + { + for( ForgeDirection side : ForgeDirection.values() ) + { + IPart p = this.getPart( side ); + if( p != null ) + { + p.randomDisplayTick( world, x, y, z, r ); + } + } + } + + @Override + public int getLightValue() + { + int light = 0; + + for( ForgeDirection d : ForgeDirection.values() ) + { + IPart p = this.getPart( d ); + if( p != null ) + light = Math.max( p.getLightLevel(), light ); + } + + if( light > 0 && AppEng.instance.isIntegrationEnabled( IntegrationType.CLApi ) ) + return ( (ICLApi) AppEng.instance.getIntegration( IntegrationType.CLApi ) ).colorLight( this.getColor(), light ); + + return light; + } + + @SideOnly( Side.CLIENT ) + public void renderStatic( double x, double y, double z ) + { + CableRenderHelper.getInstance().renderStatic( this, this.getFacadeContainer() ); + } + + @SideOnly( Side.CLIENT ) + public void renderDynamic( double x, double y, double z ) + { + CableRenderHelper.getInstance().renderDynamic( this, x, y, z ); + } + + public void writeToStream( ByteBuf data ) throws IOException + { + int sides = 0; + for( int x = 0; x < 7; x++ ) + { + IPart p = this.getPart( ForgeDirection.getOrientation( x ) ); + if( p != null ) + { + sides |= ( 1 << x ); + } + } + + data.writeByte( (byte) sides ); + + for( int x = 0; x < 7; x++ ) + { + ItemStack is = null; + IPart p = this.getPart( ForgeDirection.getOrientation( x ) ); + if( p != null ) + { + is = p.getItemStack( PartItemStack.Network ); + + data.writeShort( Item.getIdFromItem( is.getItem() ) ); + data.writeShort( is.getItemDamage() ); + + p.writeToStream( data ); + } + } + + this.getFacadeContainer().writeToStream( data ); + } + + public boolean readFromStream( ByteBuf data ) throws IOException + { + byte sides = data.readByte(); + + boolean updateBlock = false; + + for( int x = 0; x < 7; x++ ) + { + ForgeDirection side = ForgeDirection.getOrientation( x ); + if( ( ( sides & ( 1 << x ) ) == ( 1 << x ) ) ) + { + IPart p = this.getPart( side ); + + short itemID = data.readShort(); + short dmgValue = data.readShort(); + + Item myItem = Item.getItemById( itemID ); + + ItemStack current = p != null ? p.getItemStack( PartItemStack.Network ) : null; + if( current != null && current.getItem() == myItem && current.getItemDamage() == dmgValue ) + { + if( p.readFromStream( data ) ) + updateBlock = true; + } + else + { + this.removePart( side, false ); + side = this.addPart( new ItemStack( myItem, 1, dmgValue ), side, null ); + if( side != null ) + { + p = this.getPart( side ); + p.readFromStream( data ); + } + else + throw new RuntimeException( "Invalid Stream For CableBus Container." ); + } + } + else if( this.getPart( side ) != null ) + this.removePart( side, false ); + } + + if( this.getFacadeContainer().readFromStream( data ) ) + return true; + + return updateBlock; + } + + public void writeToNBT( NBTTagCompound data ) + { + data.setInteger( "hasRedstone", this.hasRedstone.ordinal() ); + + IFacadeContainer fc = this.getFacadeContainer(); + for( ForgeDirection s : ForgeDirection.values() ) + { + fc.writeToNBT( data ); + + IPart part = this.getPart( s ); + if( part != null ) + { + NBTTagCompound def = new NBTTagCompound(); + part.getItemStack( PartItemStack.World ).writeToNBT( def ); + + NBTTagCompound extra = new NBTTagCompound(); + part.writeToNBT( extra ); + + data.setTag( "def:" + this.getSide( part ).ordinal(), def ); + data.setTag( "extra:" + this.getSide( part ).ordinal(), extra ); + } + } + } + + ForgeDirection getSide( IPart part ) + { + if( this.getCenter() == part ) + return ForgeDirection.UNKNOWN; + else + { + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) + if( this.getSide( side ) == part ) + { + return side; + } + } + throw new RuntimeException( "Uhh Bad Part on Side." ); + } + + public void readFromNBT( NBTTagCompound data ) + { + if( data.hasKey( "hasRedstone" ) ) + this.hasRedstone = YesNo.values()[data.getInteger( "hasRedstone" )]; + + for( int x = 0; x < 7; x++ ) + { + ForgeDirection side = ForgeDirection.getOrientation( x ); + + NBTTagCompound def = data.getCompoundTag( "def:" + side.ordinal() ); + NBTTagCompound extra = data.getCompoundTag( "extra:" + side.ordinal() ); + if( def != null && extra != null ) + { + IPart p = this.getPart( side ); + ItemStack iss = ItemStack.loadItemStackFromNBT( def ); + if( iss == null ) + continue; + + ItemStack current = p == null ? null : p.getItemStack( PartItemStack.World ); + + if( Platform.isSameItemType( iss, current ) ) + p.readFromNBT( extra ); + else + { + this.removePart( side, true ); + side = this.addPart( iss, side, null ); + if( side != null ) + { + p = this.getPart( side ); + p.readFromNBT( extra ); + } + else + { + AELog.warning( "Invalid NBT For CableBus Container: " + iss.getItem().getClass().getName() + " is not a valid part; it was ignored." ); + } + } + } + else + this.removePart( side, false ); + } + + this.getFacadeContainer().readFromNBT( data ); + } + + public List getDrops( List drops ) + { + for( ForgeDirection s : ForgeDirection.values() ) + { + IPart part = this.getPart( s ); + if( part != null ) + { + drops.add( part.getItemStack( PartItemStack.Break ) ); + part.getDrops( drops, false ); + } + + if( s != ForgeDirection.UNKNOWN ) + { + IFacadePart fp = this.getFacadeContainer().getFacade( s ); + if( fp != null ) + drops.add( fp.getItemStack() ); + } + } + + return drops; + } + + public List getNoDrops( List drops ) + { + for( ForgeDirection s : ForgeDirection.values() ) + { + IPart part = this.getPart( s ); + if( part != null ) + { + part.getDrops( drops, false ); + } + } + + return drops; + } + + @Override + public boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ) + { + IPart cable = this.getPart( ForgeDirection.UNKNOWN ); + if( cable != null ) + { + IPartCable pc = (IPartCable) cable; + return pc.changeColor( colour, who ); + } + return false; + } } diff --git a/src/main/java/appeng/parts/CableBusStorage.java b/src/main/java/appeng/parts/CableBusStorage.java index 48e3f878b..2ed38395d 100644 --- a/src/main/java/appeng/parts/CableBusStorage.java +++ b/src/main/java/appeng/parts/CableBusStorage.java @@ -18,12 +18,14 @@ package appeng.parts; + import net.minecraftforge.common.util.ForgeDirection; import appeng.api.implementations.parts.IPartCable; import appeng.api.parts.IFacadePart; import appeng.api.parts.IPart; + /** * Thin data storage to optimize memory usage for cables. */ @@ -39,47 +41,81 @@ public class CableBusStorage return this.center; } - protected void setCenter(IPartCable center) + protected void setCenter( IPartCable center ) { this.center = center; } - protected IPart getSide(ForgeDirection side) + protected IPart getSide( ForgeDirection side ) { int x = side.ordinal(); - if ( this.sides != null && this.sides.length > x ) + if( this.sides != null && this.sides.length > x ) return this.sides[x]; return null; } - protected void setSide(ForgeDirection side, IPart part) + protected void setSide( ForgeDirection side, IPart part ) { int x = side.ordinal(); - if ( this.sides != null && this.sides.length > x && part == null ) + if( this.sides != null && this.sides.length > x && part == null ) { this.sides[x] = null; this.sides = this.shrink( this.sides, true ); } - else if ( part != null ) + else if( part != null ) { this.sides = this.grow( this.sides, x, true ); this.sides[x] = part; } } - public IFacadePart getFacade(int x) + private T[] shrink( T[] in, boolean parts ) { - if ( this.facades != null && this.facades.length > x ) + int newSize = -1; + for( int x = 0; x < in.length; x++ ) + if( in[x] != null ) + newSize = x; + + if( newSize == -1 ) + return null; + + newSize++; + if( newSize == in.length ) + return in; + + T[] newArray = (T[]) ( parts ? new IPart[newSize] : new IFacadePart[newSize] ); + System.arraycopy( in, 0, newArray, 0, newSize ); + + return newArray; + } + + private T[] grow( T[] in, int new_value, boolean parts ) + { + if( in != null && in.length > new_value ) + return in; + + int newSize = new_value + 1; + + T[] newArray = (T[]) ( parts ? new IPart[newSize] : new IFacadePart[newSize] ); + if( in != null ) + System.arraycopy( in, 0, newArray, 0, in.length ); + + return newArray; + } + + public IFacadePart getFacade( int x ) + { + if( this.facades != null && this.facades.length > x ) return this.facades[x]; return null; } - public void setFacade(int x, IFacadePart facade) + public void setFacade( int x, IFacadePart facade ) { - if ( this.facades != null && this.facades.length > x && facade == null ) + if( this.facades != null && this.facades.length > x && facade == null ) { this.facades[x] = null; this.facades = this.shrink( this.facades, false ); @@ -90,38 +126,4 @@ public class CableBusStorage this.facades[x] = facade; } } - - private T[] grow(T[] in, int new_value, boolean parts) - { - if ( in != null && in.length > new_value ) - return in; - - int newSize = new_value + 1; - - T[] newArray = (T[]) (parts ? new IPart[newSize] : new IFacadePart[newSize]); - if ( in != null ) - System.arraycopy( in, 0, newArray, 0, in.length ); - - return newArray; - } - - private T[] shrink(T[] in, boolean parts) - { - int newSize = -1; - for (int x = 0; x < in.length; x++) - if ( in[x] != null ) - newSize = x; - - if ( newSize == -1 ) - return null; - - newSize++; - if ( newSize == in.length ) - return in; - - T[] newArray = (T[]) (parts ? new IPart[newSize] : new IFacadePart[newSize]); - System.arraycopy( in, 0, newArray, 0, newSize ); - - return newArray; - } } diff --git a/src/main/java/appeng/parts/ICableBusContainer.java b/src/main/java/appeng/parts/ICableBusContainer.java index 12a7d5fb8..9a0e6b5cc 100644 --- a/src/main/java/appeng/parts/ICableBusContainer.java +++ b/src/main/java/appeng/parts/ICableBusContainer.java @@ -18,6 +18,7 @@ package appeng.parts; + import java.util.EnumSet; import java.util.Random; @@ -34,34 +35,34 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.api.parts.SelectedPart; import appeng.api.util.AEColor; + public interface ICableBusContainer { - int isProvidingStrongPower(ForgeDirection opposite); + int isProvidingStrongPower( ForgeDirection opposite ); - int isProvidingWeakPower(ForgeDirection opposite); + int isProvidingWeakPower( ForgeDirection opposite ); - boolean canConnectRedstone(EnumSet of); + boolean canConnectRedstone( EnumSet of ); - void onEntityCollision(Entity e); + void onEntityCollision( Entity e ); - boolean activate(EntityPlayer player, Vec3 vecFromPool); + boolean activate( EntityPlayer player, Vec3 vecFromPool ); void onNeighborChanged(); - boolean isSolidOnSide(ForgeDirection side); + boolean isSolidOnSide( ForgeDirection side ); boolean isEmpty(); - SelectedPart selectPart(Vec3 v3); + SelectedPart selectPart( Vec3 v3 ); - boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who); + boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ); - boolean isLadder(EntityLivingBase entity); + boolean isLadder( EntityLivingBase entity ); - @SideOnly(Side.CLIENT) - void randomDisplayTick(World world, int x, int y, int z, Random r); + @SideOnly( Side.CLIENT ) + void randomDisplayTick( World world, int x, int y, int z, Random r ); int getLightValue(); - } diff --git a/src/main/java/appeng/parts/NullCableBusContainer.java b/src/main/java/appeng/parts/NullCableBusContainer.java index f5f10e922..bb71bab74 100644 --- a/src/main/java/appeng/parts/NullCableBusContainer.java +++ b/src/main/java/appeng/parts/NullCableBusContainer.java @@ -18,6 +18,7 @@ package appeng.parts; + import java.util.EnumSet; import java.util.Random; @@ -31,35 +32,36 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.parts.SelectedPart; import appeng.api.util.AEColor; + public class NullCableBusContainer implements ICableBusContainer { @Override - public int isProvidingStrongPower(ForgeDirection opposite) + public int isProvidingStrongPower( ForgeDirection opposite ) { return 0; } @Override - public int isProvidingWeakPower(ForgeDirection opposite) + public int isProvidingWeakPower( ForgeDirection opposite ) { return 0; } @Override - public boolean canConnectRedstone(EnumSet of) + public boolean canConnectRedstone( EnumSet of ) { return false; } @Override - public void onEntityCollision(Entity e) + public void onEntityCollision( Entity e ) { } @Override - public boolean activate(EntityPlayer player, Vec3 vecFromPool) + public boolean activate( EntityPlayer player, Vec3 vecFromPool ) { return false; } @@ -71,7 +73,7 @@ public class NullCableBusContainer implements ICableBusContainer } @Override - public boolean isSolidOnSide(ForgeDirection side) + public boolean isSolidOnSide( ForgeDirection side ) { return false; } @@ -83,25 +85,25 @@ public class NullCableBusContainer implements ICableBusContainer } @Override - public SelectedPart selectPart(Vec3 v3) + public SelectedPart selectPart( Vec3 v3 ) { return new SelectedPart(); } @Override - public boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who) + public boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ) { return false; } @Override - public boolean isLadder(EntityLivingBase entity) + public boolean isLadder( EntityLivingBase entity ) { return false; } @Override - public void randomDisplayTick(World world, int x, int y, int z, Random r) + public void randomDisplayTick( World world, int x, int y, int z, Random r ) { } @@ -111,5 +113,4 @@ public class NullCableBusContainer implements ICableBusContainer { return 0; } - } diff --git a/src/main/java/appeng/parts/PartBasicState.java b/src/main/java/appeng/parts/PartBasicState.java index 7e1344380..413c0a400 100644 --- a/src/main/java/appeng/parts/PartBasicState.java +++ b/src/main/java/appeng/parts/PartBasicState.java @@ -81,13 +81,13 @@ public abstract class PartBasicState extends AEBasePart implements IPowerChannel public void setColors( boolean hasChan, boolean hasPower ) { - if ( hasChan ) + if( hasChan ) { int l = 14; Tessellator.instance.setBrightness( l << 20 | l << 4 ); Tessellator.instance.setColorOpaque_I( this.getColor().blackVariant ); } - else if ( hasPower ) + else if( hasPower ) { int l = 9; Tessellator.instance.setBrightness( l << 20 | l << 4 ); @@ -109,15 +109,15 @@ public abstract class PartBasicState extends AEBasePart implements IPowerChannel try { - if ( this.proxy.getEnergy().isNetworkPowered() ) + if( this.proxy.getEnergy().isNetworkPowered() ) this.clientFlags |= this.POWERED_FLAG; - if ( this.proxy.getNode().meetsChannelRequirements() ) + if( this.proxy.getNode().meetsChannelRequirements() ) this.clientFlags |= this.CHANNEL_FLAG; this.clientFlags = this.populateFlags( this.clientFlags ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // meh } diff --git a/src/main/java/appeng/parts/PartPlacement.java b/src/main/java/appeng/parts/PartPlacement.java index 1fcadb607..f57178217 100644 --- a/src/main/java/appeng/parts/PartPlacement.java +++ b/src/main/java/appeng/parts/PartPlacement.java @@ -75,52 +75,52 @@ public class PartPlacement public static boolean place( ItemStack held, int x, int y, int z, int face, EntityPlayer player, World world, PlaceType pass, int depth ) { - if ( depth > 3 ) + if( depth > 3 ) return false; ForgeDirection side = ForgeDirection.getOrientation( face ); - if ( held != null && Platform.isWrench( player, held, x, y, z ) && player.isSneaking() ) + if( held != null && Platform.isWrench( player, held, x, y, z ) && player.isSneaking() ) { - if ( !Platform.hasPermissions( new DimensionalCoord( world, x, y, z ), player ) ) + if( !Platform.hasPermissions( new DimensionalCoord( world, x, y, z ), player ) ) return false; Block block = world.getBlock( x, y, z ); TileEntity tile = world.getTileEntity( x, y, z ); IPartHost host = null; - if ( tile instanceof IPartHost ) + if( tile instanceof IPartHost ) host = (IPartHost) tile; - if ( host != null ) + if( host != null ) { - if ( !world.isRemote ) + if( !world.isRemote ) { LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.a, dir.b ); - if ( mop != null ) + if( mop != null ) { List is = new LinkedList(); SelectedPart sp = selectPart( player, host, mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ) ); - if ( sp.part != null ) + if( sp.part != null ) { is.add( sp.part.getItemStack( PartItemStack.Wrench ) ); sp.part.getDrops( is, true ); host.removePart( sp.side, false ); } - if ( sp.facade != null ) + if( sp.facade != null ) { is.add( sp.facade.getItemStack() ); host.getFacadeContainer().removeFacade( host, sp.side ); Platform.notifyBlocksOfNeighbors( world, x, y, z ); } - if ( host.isEmpty() ) + if( host.isEmpty() ) host.cleanup(); - if ( !is.isEmpty() ) + if( !is.isEmpty() ) { Platform.spawnDrops( world, x, y, z, is ); } @@ -140,30 +140,30 @@ public class PartPlacement TileEntity tile = world.getTileEntity( x, y, z ); IPartHost host = null; - if ( tile instanceof IPartHost ) + if( tile instanceof IPartHost ) host = (IPartHost) tile; - if ( held != null ) + if( held != null ) { IFacadePart fp = isFacade( held, side ); - if ( fp != null ) + if( fp != null ) { - if ( host != null ) + if( host != null ) { - if ( !world.isRemote ) + if( !world.isRemote ) { - if ( host.getPart( ForgeDirection.UNKNOWN ) == null ) + if( host.getPart( ForgeDirection.UNKNOWN ) == null ) return false; - if ( host.canAddPart( held, side ) ) + if( host.canAddPart( held, side ) ) { - if ( host.getFacadeContainer().addFacade( fp ) ) + if( host.getFacadeContainer().addFacade( fp ) ) { host.markForUpdate(); - if ( !player.capabilities.isCreativeMode ) + if( !player.capabilities.isCreativeMode ) { held.stackSize--; - if ( held.stackSize == 0 ) + if( held.stackSize == 0 ) { player.inventory.mainInventory[player.inventory.currentItem] = null; MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); @@ -184,27 +184,27 @@ public class PartPlacement } } - if ( host == null && tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) + if( host == null && tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) host = ( (IFMP) AppEng.instance.getIntegration( IntegrationType.FMP ) ).getOrCreateHost( tile ); - if ( host == null && tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.ImmibisMicroblocks ) ) + if( host == null && tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.ImmibisMicroblocks ) ) host = ( (IImmibisMicroblocks) AppEng.instance.getIntegration( IntegrationType.ImmibisMicroblocks ) ).getOrCreateHost( player, face, tile ); // if ( held == null ) { Block block = world.getBlock( x, y, z ); - if ( host != null && player.isSneaking() && block != null ) + if( host != null && player.isSneaking() && block != null ) { LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.a, dir.b ); - if ( mop != null ) + if( mop != null ) { mop.hitVec = mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ); SelectedPart sPart = selectPart( player, host, mop.hitVec ); - if ( sPart != null && sPart.part != null ) - if ( sPart.part.onShiftActivate( player, mop.hitVec ) ) + if( sPart != null && sPart.part != null ) + if( sPart.part.onShiftActivate( player, mop.hitVec ) ) { - if ( world.isRemote ) + if( world.isRemote ) { NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); } @@ -214,7 +214,7 @@ public class PartPlacement } } - if ( held == null || !( held.getItem() instanceof IPartItem ) ) + if( held == null || !( held.getItem() instanceof IPartItem ) ) return false; int te_x = x; @@ -222,15 +222,15 @@ public class PartPlacement int te_z = z; final IBlockDefinition multiPart = AEApi.instance().definitions().blocks().multiPart(); - if ( host == null && pass == PlaceType.PLACE_ITEM ) + if( host == null && pass == PlaceType.PLACE_ITEM ) { ForgeDirection offset = ForgeDirection.UNKNOWN; Block blkID = world.getBlock( x, y, z ); - if ( blkID != null && !blkID.isReplaceable( world, x, y, z ) ) + if( blkID != null && !blkID.isReplaceable( world, x, y, z ) ) { offset = side; - if ( Platform.isServer() ) + if( Platform.isServer() ) side = side.getOpposite(); } @@ -239,13 +239,13 @@ public class PartPlacement te_z = z + offset.offsetZ; tile = world.getTileEntity( te_x, te_y, te_z ); - if ( tile instanceof IPartHost ) + if( tile instanceof IPartHost ) host = (IPartHost) tile; - if ( host == null && tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) + if( host == null && tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) host = ( (IFMP) AppEng.instance.getIntegration( IntegrationType.FMP ) ).getOrCreateHost( tile ); - if ( host == null && tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.ImmibisMicroblocks ) ) + if( host == null && tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.ImmibisMicroblocks ) ) host = ( (IImmibisMicroblocks) AppEng.instance.getIntegration( IntegrationType.ImmibisMicroblocks ) ).getOrCreateHost( player, face, tile ); final Optional maybeMultiPartStack = multiPart.maybeStack( 1 ); @@ -256,13 +256,13 @@ public class PartPlacement final boolean multiPartPresent = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent() && maybeMultiPartItemBlock.isPresent(); final boolean canMultiPartBePlaced = maybeMultiPartBlock.get().canPlaceBlockAt( world, te_x, te_y, te_z ); - if ( hostIsNotPresent && multiPartPresent && canMultiPartBePlaced && maybeMultiPartItemBlock.get().placeBlockAt( maybeMultiPartStack.get(), player, world, te_x, te_y, te_z, side.ordinal(), 0.5f, 0.5f, 0.5f, 0 ) ) + if( hostIsNotPresent && multiPartPresent && canMultiPartBePlaced && maybeMultiPartItemBlock.get().placeBlockAt( maybeMultiPartStack.get(), player, world, te_x, te_y, te_z, side.ordinal(), 0.5f, 0.5f, 0.5f, 0 ) ) { - if ( !world.isRemote ) + if( !world.isRemote ) { tile = world.getTileEntity( te_x, te_y, te_z ); - if ( tile instanceof IPartHost ) + if( tile instanceof IPartHost ) host = (IPartHost) tile; pass = PlaceType.INTERACT_SECOND_PASS; @@ -274,18 +274,18 @@ public class PartPlacement return true; } } - else if ( host != null && !host.canAddPart( held, side ) ) + else if( host != null && !host.canAddPart( held, side ) ) { return false; } } - if ( host == null ) + if( host == null ) return false; - if ( !host.canAddPart( held, side ) ) + if( !host.canAddPart( held, side ) ) { - if ( pass == PlaceType.INTERACT_FIRST_PASS || pass == PlaceType.PLACE_ITEM ) + if( pass == PlaceType.INTERACT_FIRST_PASS || pass == PlaceType.PLACE_ITEM ) { te_x = x + side.offsetX; te_y = y + side.offsetY; @@ -294,49 +294,49 @@ public class PartPlacement Block blkID = world.getBlock( te_x, te_y, te_z ); tile = world.getTileEntity( te_x, te_y, te_z ); - if ( tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) + if( tile != null && AppEng.instance.isIntegrationEnabled( IntegrationType.FMP ) ) host = ( (IFMP) AppEng.instance.getIntegration( IntegrationType.FMP ) ).getOrCreateHost( tile ); - if ( ( blkID == null || blkID.isReplaceable( world, te_x, te_y, te_z ) || host != null ) && side != ForgeDirection.UNKNOWN ) + if( ( blkID == null || blkID.isReplaceable( world, te_x, te_y, te_z ) || host != null ) && side != ForgeDirection.UNKNOWN ) return place( held, te_x, te_y, te_z, side.getOpposite().ordinal(), player, world, pass == PlaceType.INTERACT_FIRST_PASS ? PlaceType.INTERACT_SECOND_PASS : PlaceType.PLACE_ITEM, depth + 1 ); } return false; } - if ( !world.isRemote ) + if( !world.isRemote ) { Block block = world.getBlock( x, y, z ); LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.a, dir.b ); - if ( mop != null ) + if( mop != null ) { SelectedPart sp = selectPart( player, host, mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ) ); - if ( sp.part != null ) + if( sp.part != null ) { - if ( !player.isSneaking() && sp.part.onActivate( player, mop.hitVec ) ) + if( !player.isSneaking() && sp.part.onActivate( player, mop.hitVec ) ) return false; } } DimensionalCoord dc = host.getLocation(); - if ( !Platform.hasPermissions( dc, player ) ) + if( !Platform.hasPermissions( dc, player ) ) return false; ForgeDirection mySide = host.addPart( held, side, player ); - if ( mySide != null ) + if( mySide != null ) { - for ( Block multiPartBlock : multiPart.maybeBlock().asSet() ) + for( Block multiPartBlock : multiPart.maybeBlock().asSet() ) { final SoundType ss = multiPartBlock.stepSound; world.playSoundEffect( 0.5 + x, 0.5 + y, 0.5 + z, ss.func_150496_b(), ( ss.getVolume() + 1.0F ) / 2.0F, ss.getPitch() * 0.8F ); } - if ( !player.capabilities.isCreativeMode ) + if( !player.capabilities.isCreativeMode ) { held.stackSize--; - if ( held.stackSize == 0 ) + if( held.stackSize == 0 ) { player.inventory.mainInventory[player.inventory.currentItem] = null; MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); @@ -354,7 +354,7 @@ public class PartPlacement private static float getEyeOffset( EntityPlayer p ) { - if ( p.worldObj.isRemote ) + if( p.worldObj.isRemote ) return Platform.getEyeOffset( p ); return eyeHeight; @@ -371,13 +371,13 @@ public class PartPlacement public static IFacadePart isFacade( ItemStack held, ForgeDirection side ) { - if ( held.getItem() instanceof IFacadeItem ) + if( held.getItem() instanceof IFacadeItem ) return ( (IFacadeItem) held.getItem() ).createPartFromItemStack( held, side ); - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) { IBC bc = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); - if ( bc.isFacade( held ) ) + if( bc.isFacade( held ) ) return bc.createFacadePart( held, side ); } @@ -393,7 +393,7 @@ public class PartPlacement @SubscribeEvent public void playerInteract( PlayerInteractEvent event ) { - if ( event.action == Action.RIGHT_CLICK_AIR && event.entityPlayer.worldObj.isRemote ) + if( event.action == Action.RIGHT_CLICK_AIR && event.entityPlayer.worldObj.isRemote ) { // re-check to see if this event was already channeled, cause these two events are really stupid... MovingObjectPosition mop = Platform.rayTrace( event.entityPlayer, true, false ); @@ -403,11 +403,11 @@ public class PartPlacement double d0 = mc.playerController.getBlockReachDistance(); Vec3 vec3 = mc.renderViewEntity.getPosition( f ); - if ( mop != null && mop.hitVec.distanceTo( vec3 ) < d0 ) + if( mop != null && mop.hitVec.distanceTo( vec3 ) < d0 ) { World w = event.entity.worldObj; TileEntity te = w.getTileEntity( mop.blockX, mop.blockY, mop.blockZ ); - if ( te instanceof IPartHost && this.wasCanceled ) + if( te instanceof IPartHost && this.wasCanceled ) event.setCanceled( true ); } else @@ -418,21 +418,21 @@ public class PartPlacement boolean supportedItem = items.memoryCard().isSameAs( held ); supportedItem |= items.colorApplicator().isSameAs( held ); - if ( event.entityPlayer.isSneaking() && held != null && supportedItem ) + if( event.entityPlayer.isSneaking() && held != null && supportedItem ) { NetworkHandler.instance.sendToServer( new PacketClick( event.x, event.y, event.z, event.face, 0, 0, 0 ) ); } } } - else if ( event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote ) + else if( event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote ) { - if ( this.placing.get() != null ) + if( this.placing.get() != null ) return; this.placing.set( event ); ItemStack held = event.entityPlayer.getHeldItem(); - if ( place( held, event.x, event.y, event.z, event.face, event.entityPlayer, event.entityPlayer.worldObj, PlaceType.INTERACT_FIRST_PASS, 0 ) ) + if( place( held, event.x, event.y, event.z, event.face, event.entityPlayer, event.entityPlayer.worldObj, PlaceType.INTERACT_FIRST_PASS, 0 ) ) { event.setCanceled( true ); this.wasCanceled = true; diff --git a/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java b/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java index 13e128f10..08167930a 100644 --- a/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java @@ -25,11 +25,11 @@ public class BlockUpgradeInventory extends UpgradeInventory { int max = 0; - for ( ItemStack is : upgrades.getSupported().keySet() ) + for( ItemStack is : upgrades.getSupported().keySet() ) { final Item encodedItem = is.getItem(); - if ( encodedItem instanceof ItemBlock && Block.getBlockFromItem( encodedItem ) == this.block ) + if( encodedItem instanceof ItemBlock && Block.getBlockFromItem( encodedItem ) == this.block ) { max = upgrades.getSupported().get( is ); break; diff --git a/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java b/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java index 28889da01..35fbaf5ad 100644 --- a/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java @@ -24,9 +24,9 @@ public final class DefinitionUpgradeInventory extends UpgradeInventory { int max = 0; - for ( ItemStack stack : upgrades.getSupported().keySet() ) + for( ItemStack stack : upgrades.getSupported().keySet() ) { - if ( this.definition.isSameAs( stack ) ) + if( this.definition.isSameAs( stack ) ) { max = upgrades.getSupported().get( stack ); break; diff --git a/src/main/java/appeng/parts/automation/NonNullArrayIterator.java b/src/main/java/appeng/parts/automation/NonNullArrayIterator.java index c94edec0f..601a043e1 100644 --- a/src/main/java/appeng/parts/automation/NonNullArrayIterator.java +++ b/src/main/java/appeng/parts/automation/NonNullArrayIterator.java @@ -18,24 +18,27 @@ package appeng.parts.automation; + import java.util.Iterator; import scala.NotImplementedError; + public class NonNullArrayIterator implements Iterator { - int offset = 0; final E[] g; + int offset = 0; - public NonNullArrayIterator(E[] o) { + public NonNullArrayIterator( E[] o ) + { this.g = o; } @Override public boolean hasNext() { - while (this.offset < this.g.length && this.g[this.offset] == null) + while( this.offset < this.g.length && this.g[this.offset] == null ) this.offset++; return this.offset != this.g.length; @@ -54,5 +57,4 @@ public class NonNullArrayIterator implements Iterator { throw new NotImplementedError(); } - } diff --git a/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java b/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java index 9d5e21cb3..4b569a368 100644 --- a/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java +++ b/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java @@ -85,6 +85,51 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab return this.breakBlock( true ); } + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + int minX = 1; + int minY = 1; + int maxX = 15; + int maxY = 15; + + final IPartHost host = this.getHost(); + if( host != null ) + { + final TileEntity te = host.getTile(); + + final int x = te.xCoord; + final int y = te.yCoord; + final int z = te.zCoord; + + final ForgeDirection e = bch.getWorldX(); + final ForgeDirection u = bch.getWorldY(); + + if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.side ) ) + { + minX = 0; + } + + if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.side ) ) + { + maxX = 16; + } + + if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.side ) ) + { + minY = 0; + } + + if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.side ) ) + { + maxY = 16; + } + } + + bch.addBox( 5, 5, 14, 11, 11, 15 ); + bch.addBox( minX, minY, 15, maxX, maxY, bch.isBBCollision() ? 15 : 16 ); + } + @Override @SideOnly( Side.CLIENT ) public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) @@ -112,22 +157,22 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab final TileEntity te = this.getHost().getTile(); - if ( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.side ) ) + if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.side ) ) { minX = 0; } - if ( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.side ) ) + if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.side ) ) { maxX = 16; } - if ( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.side ) ) + if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.side ) ) { minY = 0; } - if ( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.side ) ) + if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.side ) ) { maxY = 16; } @@ -148,16 +193,6 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab this.renderLights( x, y, z, rh, renderer ); } - private boolean isAnnihilationPlane( TileEntity blockTileEntity, ForgeDirection side ) - { - if ( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p instanceof PartAnnihilationPlane; - } - return false; - } - @Override public void onNeighborChanged() { @@ -166,7 +201,7 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab { this.proxy.getTick().alertDevice( this.proxy.getNode() ); } - catch ( final GridAccessException e ) + catch( final GridAccessException e ) { // :P } @@ -175,19 +210,19 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab @Override public void onEntityCollision( Entity entity ) { - if ( this.isAccepting && entity instanceof EntityItem && !entity.isDead && Platform.isServer() && this.proxy.isActive() ) + if( this.isAccepting && entity instanceof EntityItem && !entity.isDead && Platform.isServer() && this.proxy.isActive() ) { boolean capture = false; - switch ( this.side ) + switch( this.side ) { case DOWN: case UP: - if ( entity.posX > this.tile.xCoord && entity.posX < this.tile.xCoord + 1 ) + if( entity.posX > this.tile.xCoord && entity.posX < this.tile.xCoord + 1 ) { - if ( entity.posZ > this.tile.zCoord && entity.posZ < this.tile.zCoord + 1 ) + if( entity.posZ > this.tile.zCoord && entity.posZ < this.tile.zCoord + 1 ) { - if ( ( entity.posY > this.tile.yCoord + 0.9 && this.side == ForgeDirection.UP ) || ( entity.posY < this.tile.yCoord + 0.1 && this.side == ForgeDirection.DOWN ) ) + if( ( entity.posY > this.tile.yCoord + 0.9 && this.side == ForgeDirection.UP ) || ( entity.posY < this.tile.yCoord + 0.1 && this.side == ForgeDirection.DOWN ) ) { capture = true; } @@ -196,11 +231,11 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab break; case SOUTH: case NORTH: - if ( entity.posX > this.tile.xCoord && entity.posX < this.tile.xCoord + 1 ) + if( entity.posX > this.tile.xCoord && entity.posX < this.tile.xCoord + 1 ) { - if ( entity.posY > this.tile.yCoord && entity.posY < this.tile.yCoord + 1 ) + if( entity.posY > this.tile.yCoord && entity.posY < this.tile.yCoord + 1 ) { - if ( ( entity.posZ > this.tile.zCoord + 0.9 && this.side == ForgeDirection.SOUTH ) || ( entity.posZ < this.tile.zCoord + 0.1 && this.side == ForgeDirection.NORTH ) ) + if( ( entity.posZ > this.tile.zCoord + 0.9 && this.side == ForgeDirection.SOUTH ) || ( entity.posZ < this.tile.zCoord + 0.1 && this.side == ForgeDirection.NORTH ) ) { capture = true; } @@ -209,11 +244,11 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab break; case EAST: case WEST: - if ( entity.posZ > this.tile.zCoord && entity.posZ < this.tile.zCoord + 1 ) + if( entity.posZ > this.tile.zCoord && entity.posZ < this.tile.zCoord + 1 ) { - if ( entity.posY > this.tile.yCoord && entity.posY < this.tile.yCoord + 1 ) + if( entity.posY > this.tile.yCoord && entity.posY < this.tile.yCoord + 1 ) { - if ( ( entity.posX > this.tile.xCoord + 0.9 && this.side == ForgeDirection.EAST ) || ( entity.posX < this.tile.xCoord + 0.1 && this.side == ForgeDirection.WEST ) ) + if( ( entity.posX > this.tile.xCoord + 0.9 && this.side == ForgeDirection.EAST ) || ( entity.posX < this.tile.xCoord + 0.1 && this.side == ForgeDirection.WEST ) ) { capture = true; } @@ -225,7 +260,7 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab break; } - if ( capture ) + if( capture ) { ServerHelper.proxy.sendToAllNearExcept( null, this.tile.xCoord, this.tile.yCoord, this.tile.zCoord, 64, this.tile.getWorldObj(), new PacketTransitionEffect( entity.posX, entity.posY, entity.posZ, this.side, false ) ); this.storeEntityItem( (EntityItem) entity ); @@ -233,69 +268,12 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab } } - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - int minX = 1; - int minY = 1; - int maxX = 15; - int maxY = 15; - - final IPartHost host = this.getHost(); - if ( host != null ) - { - final TileEntity te = host.getTile(); - - final int x = te.xCoord; - final int y = te.yCoord; - final int z = te.zCoord; - - final ForgeDirection e = bch.getWorldX(); - final ForgeDirection u = bch.getWorldY(); - - if ( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.side ) ) - { - minX = 0; - } - - if ( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.side ) ) - { - maxX = 16; - } - - if ( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.side ) ) - { - minY = 0; - } - - if ( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.side ) ) - { - maxY = 16; - } - } - - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( minX, minY, 15, maxX, maxY, bch.isBBCollision() ? 15 : 16 ); - } - @Override public int cableConnectionRenderTo() { return 1; } - /** - * If the plane is accepting items. - * - * This might be improved if a performance problem shows up. - * - * @return true if planes accepts items. - */ - private boolean isAccepting() - { - return this.isAccepting; - } - /** * Stores an {@link EntityItem} inside the network and either marks it as dead or sets it to the leftover stackSize. * @@ -303,7 +281,7 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab */ private void storeEntityItem( EntityItem entityItem ) { - if ( !entityItem.isDead ) + if( !entityItem.isDead ) { this.storeItemStack( entityItem.getEntityItem() ); entityItem.setDead(); @@ -328,7 +306,7 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab this.isAccepting = overflow == null; } - catch ( final GridAccessException e1 ) + catch( final GridAccessException e1 ) { // :P } @@ -336,7 +314,7 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab private void spawnOverflowItemStack( IAEItemStack overflow ) { - if ( overflow == null ) + if( overflow == null ) { return; } @@ -351,6 +329,28 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab Platform.spawnDrops( world, x, y, z, Lists.newArrayList( overflow.getItemStack() ) ); } + private boolean isAnnihilationPlane( TileEntity blockTileEntity, ForgeDirection side ) + { + if( blockTileEntity instanceof IPartHost ) + { + final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); + return p instanceof PartAnnihilationPlane; + } + return false; + } + + /** + * If the plane is accepting items. + * + * This might be improved if a performance problem shows up. + * + * @return true if planes accepts items. + */ + private boolean isAccepting() + { + return this.isAccepting; + } + @Override @MENetworkEventSubscribe public void chanRender( MENetworkChannelsChanged c ) @@ -369,7 +369,7 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab public TickRateModulation breakBlock( boolean modulate ) { - if ( this.isAccepting && this.proxy.isActive() ) + if( this.isAccepting && this.proxy.isActive() ) { try { @@ -387,16 +387,16 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab final Material mat = blk.getMaterial(); final boolean ignore = mat == Material.air || mat == Material.lava || mat == Material.water || mat.isLiquid() || blk == Blocks.bedrock || blk == Blocks.end_portal || blk == Blocks.end_portal_frame || blk == Blocks.command_block; - if ( !ignore && !w.isAirBlock( x, y, z ) && w.blockExists( x, y, z ) && w.canMineBlock( Platform.getPlayer( w ), x, y, z ) ) + if( !ignore && !w.isAirBlock( x, y, z ) && w.blockExists( x, y, z ) && w.canMineBlock( Platform.getPlayer( w ), x, y, z ) ) { final float hardness = blk.getBlockHardness( w, x, y, z ); - if ( hardness >= 0.0 ) + if( hardness >= 0.0 ) { final ItemStack[] out = Platform.getBlockDrops( w, x, y, z ); float total = 1 + hardness; - for ( final ItemStack is : out ) + for( final ItemStack is : out ) { total += is.stackSize; } @@ -404,24 +404,24 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab final boolean hasPower = energy.extractAEPower( total, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > total - 0.1; final boolean canStore = this.canStoreItemStacks( out ); - if ( hasPower && canStore ) + if( hasPower && canStore ) { - if ( modulate ) + if( modulate ) { w.setBlock( x, y, z, Platform.AIR, 0, 3 ); energy.extractAEPower( total, Actionable.MODULATE, PowerMultiplier.CONFIG ); final AxisAlignedBB box = AxisAlignedBB.getBoundingBox( x - 0.2, y - 0.2, z - 0.2, x + 1.2, y + 1.2, z + 1.2 ); - for ( final Object ei : w.getEntitiesWithinAABB( EntityItem.class, box ) ) + for( final Object ei : w.getEntitiesWithinAABB( EntityItem.class, box ) ) { - if ( ei instanceof EntityItem ) + if( ei instanceof EntityItem ) { final EntityItem entityItem = (EntityItem) ei; this.storeEntityItem( entityItem ); } } - for ( final ItemStack snaggedItem : out ) + for( final ItemStack snaggedItem : out ) { this.storeItemStack( snaggedItem ); } @@ -438,7 +438,7 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab } } } - catch ( final GridAccessException e1 ) + catch( final GridAccessException e1 ) { // :P } @@ -457,7 +457,7 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab @Override public TickRateModulation tickingRequest( IGridNode node, int ticksSinceLastCall ) { - if ( this.breaking ) + if( this.breaking ) { return TickRateModulation.URGENT; } @@ -483,17 +483,17 @@ public class PartAnnihilationPlane extends PartBasicState implements IGridTickab { final IStorageGrid storage = this.proxy.getStorage(); - for ( final ItemStack itemStack : itemStacks ) + for( final ItemStack itemStack : itemStacks ) { final IAEItemStack itemToTest = AEItemStack.create( itemStack ); final IAEItemStack overflow = storage.getItemInventory().injectItems( itemToTest, Actionable.SIMULATE, this.mySrc ); - if ( overflow == null || itemToTest.getStackSize() > overflow.getStackSize() ) + if( overflow == null || itemToTest.getStackSize() > overflow.getStackSize() ) { canStore = true; } } } - catch ( final GridAccessException e ) + catch( final GridAccessException e ) { // :P } diff --git a/src/main/java/appeng/parts/automation/PartExportBus.java b/src/main/java/appeng/parts/automation/PartExportBus.java index 3473338df..f1e3bdeda 100644 --- a/src/main/java/appeng/parts/automation/PartExportBus.java +++ b/src/main/java/appeng/parts/automation/PartExportBus.java @@ -82,13 +82,6 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest this.mySrc = new MachineSource( this ); } - @Override - public void writeToNBT( NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.cratingTracker.writeToNBT( extra ); - } - @Override public void readFromNBT( NBTTagCompound extra ) { @@ -96,16 +89,23 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest this.cratingTracker.readFromNBT( extra ); } + @Override + public void writeToNBT( NBTTagCompound extra ) + { + super.writeToNBT( extra ); + this.cratingTracker.writeToNBT( extra ); + } + @Override TickRateModulation doBusWork() { - if ( !this.proxy.isActive() ) + if( !this.proxy.isActive() ) return TickRateModulation.IDLE; this.itemToSend = 1; this.didSomething = false; - switch ( this.getInstalledUpgrades( Upgrades.SPEED ) ) + switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) { default: case 0: @@ -133,38 +133,38 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest ICraftingGrid cg = this.proxy.getCrafting(); FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - if ( d != null ) + if( d != null ) { - for ( int x = 0; x < this.availableSlots() && this.itemToSend > 0; x++ ) + for( int x = 0; x < this.availableSlots() && this.itemToSend > 0; x++ ) { IAEItemStack ais = this.config.getAEStackInSlot( x ); - if ( ais == null || this.itemToSend <= 0 || this.craftOnly() ) + if( ais == null || this.itemToSend <= 0 || this.craftOnly() ) { - if ( this.isCraftingEnabled() ) + if( this.isCraftingEnabled() ) this.didSomething = this.cratingTracker.handleCrafting( x, this.itemToSend, ais, d, this.getTile().getWorldObj(), this.proxy.getGrid(), cg, this.mySrc ) || this.didSomething; continue; } long before = this.itemToSend; - if ( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) + if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) { - for ( IAEItemStack o : ImmutableList.copyOf( inv.getStorageList().findFuzzy( ais, fzMode ) ) ) + for( IAEItemStack o : ImmutableList.copyOf( inv.getStorageList().findFuzzy( ais, fzMode ) ) ) { this.pushItemIntoTarget( d, energy, inv, o ); - if ( this.itemToSend <= 0 ) + if( this.itemToSend <= 0 ) break; } } else this.pushItemIntoTarget( d, energy, inv, ais ); - if ( this.itemToSend == before && this.isCraftingEnabled() ) + if( this.itemToSend == before && this.isCraftingEnabled() ) this.didSomething = this.cratingTracker.handleCrafting( x, this.itemToSend, ais, d, this.getTile().getWorldObj(), this.proxy.getGrid(), cg, this.mySrc ) || this.didSomething; } } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -172,6 +172,15 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest return this.didSomething ? TickRateModulation.FASTER : TickRateModulation.SLOWER; } + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 4, 4, 12, 12, 12, 14 ); + bch.addBox( 5, 5, 14, 11, 11, 15 ); + bch.addBox( 6, 6, 15, 10, 10, 16 ); + bch.addBox( 6, 6, 11, 10, 10, 12 ); + } + @Override @SideOnly( Side.CLIENT ) public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) @@ -213,15 +222,6 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest this.renderLights( x, y, z, rh, renderer ); } - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 4, 4, 12, 12, 12, 14 ); - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( 6, 6, 15, 10, 10, 16 ); - bch.addBox( 6, 6, 11, 10, 10, 12 ); - } - @Override public int cableConnectionRenderTo() { @@ -231,9 +231,9 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest @Override public boolean onPartActivate( EntityPlayer player, Vec3 pos ) { - if ( !player.isSneaking() ) + if( !player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( player, this.getHost().getTile(), this.side, GuiBridge.GUI_BUS ); @@ -244,9 +244,9 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest } @Override - public RedstoneMode getRSMode() + public TickingRequest getTickingRequest( IGridNode node ) { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); + return new TickingRequest( TickRates.ExportBus.min, TickRates.ExportBus.max, this.isSleeping(), false ); } @Override @@ -256,9 +256,9 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest } @Override - public TickingRequest getTickingRequest( IGridNode node ) + public RedstoneMode getRSMode() { - return new TickingRequest( TickRates.ExportBus.min, TickRates.ExportBus.max, this.isSleeping(), false ); + return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); } @Override @@ -285,18 +285,18 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest ItemStack o = d.simulateAdd( is ); long canFit = o == null ? this.itemToSend : this.itemToSend - o.stackSize; - if ( canFit > 0 ) + if( canFit > 0 ) { ais = ais.copy(); ais.setStackSize( canFit ); IAEItemStack itemsToAdd = Platform.poweredExtraction( energy, inv, ais, this.mySrc ); - if ( itemsToAdd != null ) + if( itemsToAdd != null ) { this.itemToSend -= itemsToAdd.getStackSize(); ItemStack failed = d.addItems( itemsToAdd.getItemStack() ); - if ( failed != null ) + if( failed != null ) { ais.setStackSize( failed.stackSize ); inv.injectItems( ais, Actionable.MODULATE, this.mySrc ); @@ -320,20 +320,20 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest try { - if ( d != null && this.proxy.isActive() ) + if( d != null && this.proxy.isActive() ) { IEnergyGrid energy = this.proxy.getEnergy(); double power = items.getStackSize(); - if ( energy.extractAEPower( power, mode, PowerMultiplier.CONFIG ) > power - 0.01 ) + if( energy.extractAEPower( power, mode, PowerMultiplier.CONFIG ) > power - 0.01 ) { - if ( mode == Actionable.MODULATE ) + if( mode == Actionable.MODULATE ) return AEItemStack.create( d.addItems( items.getItemStack() ) ); return AEItemStack.create( d.simulateAdd( items.getItemStack() ) ); } } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { AELog.error( e ); } diff --git a/src/main/java/appeng/parts/automation/PartFormationPlane.java b/src/main/java/appeng/parts/automation/PartFormationPlane.java index cc46e4dda..f20059241 100644 --- a/src/main/java/appeng/parts/automation/PartFormationPlane.java +++ b/src/main/java/appeng/parts/automation/PartFormationPlane.java @@ -100,7 +100,6 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine this.updateHandler(); } - private void updateHandler() { this.myHandler.setBaseAccess( AccessRestriction.WRITE ); @@ -111,14 +110,14 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine IItemList priorityList = AEApi.instance().storage().createItemList(); int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for ( int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++ ) + for( int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++ ) { IAEItemStack is = this.Config.getAEStackInSlot( x ); - if ( is != null ) + if( is != null ) priorityList.add( is ); } - if ( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) + if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) this.myHandler.setPartitionList( new FuzzyPriorityList( priorityList, (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ) ) ); else this.myHandler.setPartitionList( new PrecisePriorityList( priorityList ) ); @@ -127,28 +126,39 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine { this.proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } } - @Override protected int getUpgradeSlots() { return 5; } - @Override - public void writeToNBT( NBTTagCompound data ) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { - super.writeToNBT( data ); - this.Config.writeToNBT( data, "config" ); - data.setInteger( "priority", this.priority ); + this.updateHandler(); + this.host.markForSave(); } + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) + { + super.onChangeInventory( inv, slot, mc, removedStack, newStack ); + + if( inv == this.Config ) + this.updateHandler(); + } + + @Override + public void upgradesChanged() + { + this.updateHandler(); + } @Override public void readFromNBT( NBTTagCompound data ) @@ -159,48 +169,29 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine this.updateHandler(); } + @Override + public void writeToNBT( NBTTagCompound data ) + { + super.writeToNBT( data ); + this.Config.writeToNBT( data, "config" ); + data.setInteger( "priority", this.priority ); + } @Override public IInventory getInventoryByName( String name ) { - if ( name.equals( "config" ) ) + if( name.equals( "config" ) ) return this.Config; return super.getInventoryByName( name ); } - - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { - this.updateHandler(); - this.host.markForSave(); - } - - - @Override - public void upgradesChanged() - { - this.updateHandler(); - } - - - @Override - public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) - { - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); - - if ( inv == this.Config ) - this.updateHandler(); - } - - @Override @MENetworkEventSubscribe public void powerRender( MENetworkPowerStatusChange c ) { boolean currentActive = this.proxy.isActive(); - if ( this.wasActive != currentActive ) + if( this.wasActive != currentActive ) { this.wasActive = currentActive; this.updateHandler();// proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); @@ -208,12 +199,11 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine } } - @MENetworkEventSubscribe public void updateChannels( MENetworkChannelsChanged changedChannels ) { boolean currentActive = this.proxy.isActive(); - if ( this.wasActive != currentActive ) + if( this.wasActive != currentActive ) { this.wasActive = currentActive; this.updateHandler();// proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); @@ -221,6 +211,42 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine } } + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + int minX = 1; + int minY = 1; + int maxX = 15; + int maxY = 15; + + IPartHost host = this.getHost(); + if( host != null ) + { + TileEntity te = host.getTile(); + + int x = te.xCoord; + int y = te.yCoord; + int z = te.zCoord; + + ForgeDirection e = bch.getWorldX(); + ForgeDirection u = bch.getWorldY(); + + if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.side ) ) + minX = 0; + + if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.side ) ) + maxX = 16; + + if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.side ) ) + minY = 0; + + if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.side ) ) + maxY = 16; + } + + bch.addBox( 5, 5, 14, 11, 11, 15 ); + bch.addBox( minX, minY, 15, maxX, maxY, 16 ); + } @Override @SideOnly( Side.CLIENT ) @@ -235,7 +261,6 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine rh.renderInventoryBox( renderer ); } - @Override @SideOnly( Side.CLIENT ) public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) @@ -250,16 +275,16 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine TileEntity te = this.getHost().getTile(); - if ( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.side ) ) + if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.side ) ) minX = 0; - if ( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.side ) ) + if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.side ) ) maxX = 16; - if ( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.side ) ) + if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.side ) ) minY = 0; - if ( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.side ) ) + if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.side ) ) maxY = 16; boolean isActive = ( this.clientFlags & ( this.POWERED_FLAG | this.CHANNEL_FLAG ) ) == ( this.POWERED_FLAG | this.CHANNEL_FLAG ); @@ -278,18 +303,6 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine this.renderLights( x, y, z, rh, renderer ); } - - private boolean isTransitionPlane( TileEntity blockTileEntity, ForgeDirection side ) - { - if ( blockTileEntity instanceof IPartHost ) - { - IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p instanceof PartFormationPlane; - } - return false; - } - - @Override public void onNeighborChanged() { @@ -304,58 +317,18 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine this.blocked = !w.getBlock( x, y, z ).isReplaceable( w, x, y, z ); } - - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - int minX = 1; - int minY = 1; - int maxX = 15; - int maxY = 15; - - IPartHost host = this.getHost(); - if ( host != null ) - { - TileEntity te = host.getTile(); - - int x = te.xCoord; - int y = te.yCoord; - int z = te.zCoord; - - ForgeDirection e = bch.getWorldX(); - ForgeDirection u = bch.getWorldY(); - - if ( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.side ) ) - minX = 0; - - if ( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.side ) ) - maxX = 16; - - if ( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.side ) ) - minY = 0; - - if ( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.side ) ) - maxY = 16; - } - - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( minX, minY, 15, maxX, maxY, 16 ); - } - - @Override public int cableConnectionRenderTo() { return 1; } - @Override public boolean onPartActivate( EntityPlayer player, Vec3 pos ) { - if ( !player.isSneaking() ) + if( !player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( player, this.getHost().getTile(), this.side, GuiBridge.GUI_FORMATION_PLANE ); @@ -365,11 +338,20 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine return false; } + private boolean isTransitionPlane( TileEntity blockTileEntity, ForgeDirection side ) + { + if( blockTileEntity instanceof IPartHost ) + { + IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); + return p instanceof PartFormationPlane; + } + return false; + } @Override public List getCellArray( StorageChannel channel ) { - if ( this.proxy.isActive() && channel == StorageChannel.ITEMS ) + if( this.proxy.isActive() && channel == StorageChannel.ITEMS ) { List Handler = new ArrayList( 1 ); Handler.add( this.myHandler ); @@ -378,14 +360,12 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine return new ArrayList(); } - @Override public int getPriority() { return this.priority; } - @Override public void setPriority( int newValue ) { @@ -394,18 +374,16 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine this.updateHandler(); } - @Override public void blinkCell( int slot ) { // :P } - @Override public IAEItemStack injectItems( IAEItemStack input, Actionable type, BaseActionSource src ) { - if ( this.blocked || input == null || input.getStackSize() <= 0 ) + if( this.blocked || input == null || input.getStackSize() <= 0 ) return input; YesNo placeBlock = (YesNo) this.getConfigManager().getSetting( Settings.PLACE_BLOCK ); @@ -424,40 +402,40 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine int y = te.yCoord + side.offsetY; int z = te.zCoord + side.offsetZ; - if ( w.getBlock( x, y, z ).isReplaceable( w, x, y, z ) ) + if( w.getBlock( x, y, z ).isReplaceable( w, x, y, z ) ) { - if ( placeBlock == YesNo.YES && ( i instanceof ItemBlock || i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemFirework || i instanceof IPartItem || i instanceof ItemReed ) ) + if( placeBlock == YesNo.YES && ( i instanceof ItemBlock || i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemFirework || i instanceof IPartItem || i instanceof ItemReed ) ) { EntityPlayer player = Platform.getPlayer( (WorldServer) w ); Platform.configurePlayer( player, side, this.tile ); - if ( i instanceof ItemFirework ) + if( i instanceof ItemFirework ) { Chunk c = w.getChunkFromBlockCoords( x, z ); int sum = 0; - for ( List Z : c.entityLists ) + for( List Z : c.entityLists ) sum += Z.size(); - if ( sum > 32 ) + if( sum > 32 ) return input; } maxStorage = is.stackSize; worked = true; - if ( type == Actionable.MODULATE ) + if( type == Actionable.MODULATE ) { - if ( i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemReed ) + if( i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemReed ) { boolean Worked = false; - if ( side.offsetX == 0 && side.offsetZ == 0 ) + if( side.offsetX == 0 && side.offsetZ == 0 ) Worked = i.onItemUse( is, player, w, x + side.offsetX, y + side.offsetY, z + side.offsetZ, side.getOpposite().ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - if ( !Worked && side.offsetX == 0 && side.offsetZ == 0 ) + if( !Worked && side.offsetX == 0 && side.offsetZ == 0 ) Worked = i.onItemUse( is, player, w, x - side.offsetX, y - side.offsetY, z - side.offsetZ, side.ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - if ( !Worked && side.offsetY == 0 ) + if( !Worked && side.offsetY == 0 ) Worked = i.onItemUse( is, player, w, x, y - 1, z, ForgeDirection.UP.ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - if ( !Worked ) + if( !Worked ) i.onItemUse( is, player, w, x, y, z, side.getOpposite().ordinal(), side.offsetX, side.offsetY, side.offsetZ ); maxStorage -= is.stackSize; @@ -476,12 +454,12 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine worked = true; Chunk c = w.getChunkFromBlockCoords( x, z ); int sum = 0; - for ( List Z : c.entityLists ) + for( List Z : c.entityLists ) sum += Z.size(); - if ( sum < AEConfig.instance.formationPlaneEntityLimit ) + if( sum < AEConfig.instance.formationPlaneEntityLimit ) { - if ( type == Actionable.MODULATE ) + if( type == Actionable.MODULATE ) { is.stackSize = (int) maxStorage; @@ -497,16 +475,16 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine ei.motionY = side.offsetY * 0.2; ei.motionZ = side.offsetZ * 0.2; - if ( is.getItem().hasCustomEntity( is ) ) + if( is.getItem().hasCustomEntity( is ) ) { result = is.getItem().createEntity( w, ei, is ); - if ( result != null ) + if( result != null ) ei.setDead(); else result = ei; } - if ( !w.spawnEntityInWorld( result ) ) + if( !w.spawnEntityInWorld( result ) ) { result.setDead(); worked = false; @@ -520,11 +498,11 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine this.blocked = !w.getBlock( x, y, z ).isReplaceable( w, x, y, z ); - if ( worked ) + if( worked ) { IAEItemStack out = input.copy(); out.decStackSize( maxStorage ); - if ( out.getStackSize() == 0 ) + if( out.getStackSize() == 0 ) return null; return out; } @@ -532,28 +510,24 @@ public class PartFormationPlane extends PartUpgradeable implements ICellContaine return input; } - @Override public IAEItemStack extractItems( IAEItemStack request, Actionable mode, BaseActionSource src ) { return null; } - @Override public IItemList getAvailableItems( IItemList out ) { return out; } - @Override public StorageChannel getChannel() { return StorageChannel.ITEMS; } - @Override public void saveChanges( IMEInventory cellInventory ) { diff --git a/src/main/java/appeng/parts/automation/PartImportBus.java b/src/main/java/appeng/parts/automation/PartImportBus.java index ff36fdd4b..776455149 100644 --- a/src/main/java/appeng/parts/automation/PartImportBus.java +++ b/src/main/java/appeng/parts/automation/PartImportBus.java @@ -77,15 +77,23 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin @Override public boolean canInsert( ItemStack stack ) { - if ( stack == null || stack.getItem() == null ) + if( stack == null || stack.getItem() == null ) return false; IAEItemStack out = this.destination.injectItems( this.lastItemChecked = AEApi.instance().storage().createItemStack( stack ), Actionable.SIMULATE, this.source ); - if ( out == null ) + if( out == null ) return true; return out.getStackSize() != stack.stackSize; } + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 6, 6, 11, 10, 10, 13 ); + bch.addBox( 5, 5, 13, 11, 11, 14 ); + bch.addBox( 4, 4, 14, 12, 12, 16 ); + } + @Override @SideOnly( Side.CLIENT ) public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) @@ -125,14 +133,6 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin this.renderLights( x, y, z, rh, renderer ); } - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 11, 10, 10, 13 ); - bch.addBox( 5, 5, 13, 11, 11, 14 ); - bch.addBox( 4, 4, 14, 12, 12, 16 ); - } - @Override public int cableConnectionRenderTo() { @@ -142,9 +142,9 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin @Override public boolean onPartActivate( EntityPlayer player, Vec3 pos ) { - if ( !player.isSneaking() ) + if( !player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( player, this.getHost().getTile(), this.side, GuiBridge.GUI_BUS ); @@ -169,7 +169,7 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin @Override TickRateModulation doBusWork() { - if ( !this.proxy.isActive() ) + if( !this.proxy.isActive() ) return TickRateModulation.IDLE; this.worked = false; @@ -177,11 +177,11 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin InventoryAdaptor myAdaptor = this.getHandler(); FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - if ( myAdaptor != null ) + if( myAdaptor != null ) { try { - switch ( this.getInstalledUpgrades( Upgrades.SPEED ) ) + switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) { default: case 0: @@ -206,30 +206,30 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin IEnergyGrid energy = this.proxy.getEnergy(); boolean Configured = false; - for ( int x = 0; x < this.availableSlots(); x++ ) + for( int x = 0; x < this.availableSlots(); x++ ) { IAEItemStack ais = this.config.getAEStackInSlot( x ); - if ( ais != null && this.itemToSend > 0 ) + if( ais != null && this.itemToSend > 0 ) { Configured = true; - while ( this.itemToSend > 0 ) + while( this.itemToSend > 0 ) { - if ( this.importStuff( myAdaptor, ais, inv, energy, fzMode ) ) + if( this.importStuff( myAdaptor, ais, inv, energy, fzMode ) ) break; } } } - if ( !Configured ) + if( !Configured ) { - while ( this.itemToSend > 0 ) + while( this.itemToSend > 0 ) { - if ( this.importStuff( myAdaptor, null, inv, energy, fzMode ) ) + if( this.importStuff( myAdaptor, null, inv, energy, fzMode ) ) break; } } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :3 } @@ -244,28 +244,28 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin { int toSend = this.itemToSend; - if ( toSend > 64 ) + if( toSend > 64 ) toSend = 64; ItemStack newItems; - if ( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) + if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) newItems = myAdaptor.removeSimilarItems( toSend, whatToImport == null ? null : whatToImport.getItemStack(), fzMode, this.configDestination( inv ) ); else newItems = myAdaptor.removeItems( toSend, whatToImport == null ? null : whatToImport.getItemStack(), this.configDestination( inv ) ); - if ( newItems != null ) + if( newItems != null ) { newItems.stackSize = (int) ( Math.min( newItems.stackSize, energy.extractAEPower( newItems.stackSize, Actionable.SIMULATE, PowerMultiplier.CONFIG ) ) + 0.01 ); this.itemToSend -= newItems.stackSize; - if ( this.lastItemChecked == null || !this.lastItemChecked.isSameType( newItems ) ) + if( this.lastItemChecked == null || !this.lastItemChecked.isSameType( newItems ) ) this.lastItemChecked = AEApi.instance().storage().createItemStack( newItems ); else this.lastItemChecked.setStackSize( newItems.stackSize ); IAEItemStack failed = Platform.poweredInsert( energy, this.destination, this.lastItemChecked, this.source ); // destination.injectItems( lastItemChecked, Actionable.MODULATE ); - if ( failed != null ) + if( failed != null ) { myAdaptor.addItems( failed.getItemStack() ); return true; @@ -285,15 +285,15 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin return this; } - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } - @Override protected boolean isSleeping() { return this.getHandler() == null || super.isSleeping(); } + + @Override + public RedstoneMode getRSMode() + { + return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); + } } diff --git a/src/main/java/appeng/parts/automation/PartLevelEmitter.java b/src/main/java/appeng/parts/automation/PartLevelEmitter.java index bd3cd8532..e6cf3bf1c 100644 --- a/src/main/java/appeng/parts/automation/PartLevelEmitter.java +++ b/src/main/java/appeng/parts/automation/PartLevelEmitter.java @@ -80,8 +80,7 @@ import appeng.tile.inventory.InvOperation; import appeng.util.Platform; -public class PartLevelEmitter extends PartUpgradeable - implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, IMEMonitorHandlerReceiver, ICraftingProvider +public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, IMEMonitorHandlerReceiver, ICraftingProvider { final int FLAG_ON = 4; @@ -120,7 +119,7 @@ public class PartLevelEmitter extends PartUpgradeable public void setReportingValue( long v ) { this.reportingValue = v; - if ( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) + if( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) this.configureWatchers(); else this.updateState(); @@ -135,7 +134,7 @@ public class PartLevelEmitter extends PartUpgradeable private void updateState() { boolean isOn = this.isLevelEmitterOn(); - if ( this.prevState != isOn ) + if( this.prevState != isOn ) { this.host.markForUpdate(); TileEntity te = this.host.getTile(); @@ -147,23 +146,23 @@ public class PartLevelEmitter extends PartUpgradeable private boolean isLevelEmitterOn() { - if ( Platform.isClient() ) + if( Platform.isClient() ) { return ( this.clientFlags & this.FLAG_ON ) == this.FLAG_ON; } - if ( !this.proxy.isActive() ) + if( !this.proxy.isActive() ) { return false; } - if ( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) + if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) { try { return this.proxy.getCrafting().isRequesting( this.config.getAEStackInSlot( 0 ) ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -206,41 +205,40 @@ public class PartLevelEmitter extends PartUpgradeable this.updateState(); } - // update the system... public void configureWatchers() { IAEItemStack myStack = this.config.getAEStackInSlot( 0 ); - if ( this.myWatcher != null ) + if( this.myWatcher != null ) this.myWatcher.clear(); - if ( this.myEnergyWatcher != null ) + if( this.myEnergyWatcher != null ) this.myEnergyWatcher.clear(); - if ( this.myCraftingWatcher != null ) + if( this.myCraftingWatcher != null ) this.myCraftingWatcher.clear(); try { this.proxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.proxy.getNode() ) ); } - catch ( GridAccessException e1 ) + catch( GridAccessException e1 ) { // :/ } - if ( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) + if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) { - if ( this.myCraftingWatcher != null && myStack != null ) + if( this.myCraftingWatcher != null && myStack != null ) this.myCraftingWatcher.add( myStack ); return; } - if ( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) + if( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) { - if ( this.myEnergyWatcher != null ) + if( this.myEnergyWatcher != null ) this.myEnergyWatcher.add( (double) this.reportingValue ); try @@ -252,7 +250,7 @@ public class PartLevelEmitter extends PartUpgradeable // no more item stuff.. this.proxy.getStorage().getItemInventory().removeListener( this ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -262,7 +260,7 @@ public class PartLevelEmitter extends PartUpgradeable try { - if ( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 || myStack == null ) + if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 || myStack == null ) { this.proxy.getStorage().getItemInventory().addListener( this, this.proxy.getGrid() ); } @@ -270,41 +268,40 @@ public class PartLevelEmitter extends PartUpgradeable { this.proxy.getStorage().getItemInventory().removeListener( this ); - if ( this.myWatcher != null ) + if( this.myWatcher != null ) this.myWatcher.add( myStack ); } this.updateReportingValue( this.proxy.getStorage().getItemInventory() ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // >.> } } - private void updateReportingValue( IMEMonitor monitor ) { IAEItemStack myStack = this.config.getAEStackInSlot( 0 ); - if ( myStack == null ) + if( myStack == null ) { this.lastReportedValue = 0; - for ( IAEItemStack st : monitor.getStorageList() ) + for( IAEItemStack st : monitor.getStorageList() ) this.lastReportedValue += st.getStackSize(); } - else if ( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) + else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) { this.lastReportedValue = 0; FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); Collection fuzzyList = monitor.getStorageList().findFuzzy( myStack, fzMode ); - for ( IAEItemStack st : fuzzyList ) + for( IAEItemStack st : fuzzyList ) this.lastReportedValue += st.getStackSize(); } else { IAEItemStack r = monitor.getStorageList().findPrecise( myStack ); - if ( r == null ) + if( r == null ) this.lastReportedValue = 0; else this.lastReportedValue = r.getStackSize(); @@ -313,7 +310,6 @@ public class PartLevelEmitter extends PartUpgradeable this.updateState(); } - @Override public void updateWatcher( IStackWatcher newWatcher ) { @@ -321,18 +317,16 @@ public class PartLevelEmitter extends PartUpgradeable this.configureWatchers(); } - @Override public void onStackChange( IItemList o, IAEStack fullStack, IAEStack diffStack, BaseActionSource src, StorageChannel chan ) { - if ( chan == StorageChannel.ITEMS && fullStack.equals( this.config.getAEStackInSlot( 0 ) ) && this.getInstalledUpgrades( Upgrades.FUZZY ) == 0 ) + if( chan == StorageChannel.ITEMS && fullStack.equals( this.config.getAEStackInSlot( 0 ) ) && this.getInstalledUpgrades( Upgrades.FUZZY ) == 0 ) { this.lastReportedValue = fullStack.getStackSize(); this.updateState(); } } - @Override public void updateWatcher( IEnergyWatcher newWatcher ) { @@ -340,7 +334,6 @@ public class PartLevelEmitter extends PartUpgradeable this.configureWatchers(); } - @Override public void onThresholdPass( IEnergyGrid energyGrid ) { @@ -348,7 +341,6 @@ public class PartLevelEmitter extends PartUpgradeable this.updateState(); } - @Override public boolean isValid( Object effectiveGrid ) { @@ -356,20 +348,18 @@ public class PartLevelEmitter extends PartUpgradeable { return this.proxy.getGrid() == effectiveGrid; } - catch ( GridAccessException e ) + catch( GridAccessException e ) { return false; } } - @Override public void postChange( IBaseMonitor monitor, Iterable change, BaseActionSource actionSource ) { this.updateReportingValue( (IMEMonitor) monitor ); } - @Override public void onListUpdate() { @@ -377,12 +367,23 @@ public class PartLevelEmitter extends PartUpgradeable { this.updateReportingValue( this.proxy.getStorage().getItemInventory() ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // ;P } } + @Override + public AECableType getCableConnectionType( ForgeDirection dir ) + { + return AECableType.SMART; + } + + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 7, 7, 11, 9, 9, 16 ); + } @Override @SideOnly( Side.CLIENT ) @@ -396,7 +397,6 @@ public class PartLevelEmitter extends PartUpgradeable // rh.renderInventoryBox( renderer ); } - public void renderTorchAtAngle( double baseX, double baseY, double baseZ ) { boolean isOn = this.isLevelEmitterOn(); @@ -457,13 +457,13 @@ public class PartLevelEmitter extends PartUpgradeable double toff = 0.0d; - if ( !isOn ) + if( !isOn ) { toff = 1.0d / 16.0d; } Tessellator var12 = Tessellator.instance; - if ( isOn ) + if( isOn ) { var12.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); var12.setBrightness( 11 << 20 | 11 << 4 ); @@ -505,7 +505,6 @@ public class PartLevelEmitter extends PartUpgradeable this.addVertexWithUV( var36, baseY + 1.0D, baseZ - var44, var17, var18 ); } - public void addVertexWithUV( double x, double y, double z, double u, double v ) { Tessellator var12 = Tessellator.instance; @@ -514,13 +513,13 @@ public class PartLevelEmitter extends PartUpgradeable y -= this.centerY; z -= this.centerZ; - if ( this.side == ForgeDirection.DOWN ) + if( this.side == ForgeDirection.DOWN ) { y = -y; z = -z; } - if ( this.side == ForgeDirection.EAST ) + if( this.side == ForgeDirection.EAST ) { double m = x; x = y; @@ -528,14 +527,14 @@ public class PartLevelEmitter extends PartUpgradeable y = -y; } - if ( this.side == ForgeDirection.WEST ) + if( this.side == ForgeDirection.WEST ) { double m = x; x = -y; y = m; } - if ( this.side == ForgeDirection.SOUTH ) + if( this.side == ForgeDirection.SOUTH ) { double m = z; z = y; @@ -543,7 +542,7 @@ public class PartLevelEmitter extends PartUpgradeable y = -y; } - if ( this.side == ForgeDirection.NORTH ) + if( this.side == ForgeDirection.NORTH ) { double m = z; z = -y; @@ -557,7 +556,6 @@ public class PartLevelEmitter extends PartUpgradeable var12.addVertexWithUV( x, y, z, u, v ); } - @Override @SideOnly( Side.CLIENT ) public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) @@ -587,32 +585,22 @@ public class PartLevelEmitter extends PartUpgradeable // super.renderWorldBlock( world, x, y, z, block, modelId, renderer ); } - @Override public int isProvidingStrongPower() { return this.prevState ? 15 : 0; } - @Override public int isProvidingWeakPower() { return this.prevState ? 15 : 0; } - - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 7, 7, 11, 9, 9, 16 ); - } - - @Override public void randomDisplayTick( World world, int x, int y, int z, Random r ) { - if ( this.isLevelEmitterOn() ) + if( this.isLevelEmitterOn() ) { ForgeDirection d = this.side; @@ -624,27 +612,18 @@ public class PartLevelEmitter extends PartUpgradeable } } - - @Override - public AECableType getCableConnectionType( ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override public int cableConnectionRenderTo() { return 16; } - @Override public boolean onPartActivate( EntityPlayer player, Vec3 pos ) { - if ( !player.isSneaking() ) + if( !player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( player, this.getHost().getTile(), this.side, GuiBridge.GUI_LEVEL_EMITTER ); @@ -654,6 +633,26 @@ public class PartLevelEmitter extends PartUpgradeable return false; } + @Override + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) + { + this.configureWatchers(); + } + + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) + { + if( inv == this.config ) + this.configureWatchers(); + + super.onChangeInventory( inv, slot, mc, removedStack, newStack ); + } + + @Override + public void upgradesChanged() + { + this.configureWatchers(); + } @Override public boolean canConnectRedstone() @@ -661,18 +660,6 @@ public class PartLevelEmitter extends PartUpgradeable return true; } - - @Override - public void writeToNBT( NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setLong( "lastReportedValue", this.lastReportedValue ); - data.setLong( "reportingValue", this.reportingValue ); - data.setBoolean( "prevState", this.prevState ); - this.config.writeToNBT( data, "config" ); - } - - @Override public void readFromNBT( NBTTagCompound data ) { @@ -683,40 +670,25 @@ public class PartLevelEmitter extends PartUpgradeable this.config.readFromNBT( data, "config" ); } + @Override + public void writeToNBT( NBTTagCompound data ) + { + super.writeToNBT( data ); + data.setLong( "lastReportedValue", this.lastReportedValue ); + data.setLong( "reportingValue", this.reportingValue ); + data.setBoolean( "prevState", this.prevState ); + this.config.writeToNBT( data, "config" ); + } @Override public IInventory getInventoryByName( String name ) { - if ( name.equals( "config" ) ) + if( name.equals( "config" ) ) return this.config; return super.getInventoryByName( name ); } - - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { - this.configureWatchers(); - } - - - @Override - public void upgradesChanged() - { - this.configureWatchers(); - } - - - @Override - public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) - { - if ( inv == this.config ) - this.configureWatchers(); - - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } - @Override public boolean pushPattern( ICraftingPatternDetails patternDetails, InventoryCrafting table ) { @@ -732,12 +704,12 @@ public class PartLevelEmitter extends PartUpgradeable @Override public void provideCrafting( ICraftingProviderHelper craftingTracker ) { - if ( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) + if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) { - if ( this.getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ) == YesNo.YES ) + if( this.getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ) == YesNo.YES ) { IAEItemStack what = this.config.getAEStackInSlot( 0 ); - if ( what != null ) + if( what != null ) craftingTracker.setEmitable( what ); } } diff --git a/src/main/java/appeng/parts/automation/PartSharedItemBus.java b/src/main/java/appeng/parts/automation/PartSharedItemBus.java index e5f7884eb..6d3e548ec 100644 --- a/src/main/java/appeng/parts/automation/PartSharedItemBus.java +++ b/src/main/java/appeng/parts/automation/PartSharedItemBus.java @@ -53,10 +53,9 @@ public abstract class PartSharedItemBus extends PartUpgradeable implements IGrid } @Override - public void writeToNBT( net.minecraft.nbt.NBTTagCompound extra ) + public void upgradesChanged() { - super.writeToNBT( extra ); - this.config.writeToNBT( extra, "config" ); + this.updateState(); } @Override @@ -67,30 +66,31 @@ public abstract class PartSharedItemBus extends PartUpgradeable implements IGrid } @Override - public IInventory getInventoryByName( String name ) + public void writeToNBT( net.minecraft.nbt.NBTTagCompound extra ) { - if ( name.equals( "config" ) ) - return this.config; - - return super.getInventoryByName( name ); + super.writeToNBT( extra ); + this.config.writeToNBT( extra, "config" ); } @Override - public void upgradesChanged() + public IInventory getInventoryByName( String name ) { - this.updateState(); + if( name.equals( "config" ) ) + return this.config; + + return super.getInventoryByName( name ); } private void updateState() { try { - if ( !this.isSleeping() ) + if( !this.isSleeping() ) this.proxy.getTick().wakeDevice( this.proxy.getNode() ); else this.proxy.getTick().sleepDevice( this.proxy.getNode() ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -103,7 +103,7 @@ public abstract class PartSharedItemBus extends PartUpgradeable implements IGrid int newAdaptorHash = Platform.generateTileHash( target ); - if ( this.adaptorHash == newAdaptorHash && newAdaptorHash != 0 ) + if( this.adaptorHash == newAdaptorHash && newAdaptorHash != 0 ) return this.adaptor; this.adaptorHash = newAdaptorHash; @@ -116,7 +116,7 @@ public abstract class PartSharedItemBus extends PartUpgradeable implements IGrid { World w = self.getWorldObj(); - if ( w.getChunkProvider().chunkExists( x >> 4, z >> 4 ) ) + if( w.getChunkProvider().chunkExists( x >> 4, z >> 4 ) ) { return w.getTileEntity( x, y, z ); } @@ -128,10 +128,10 @@ public abstract class PartSharedItemBus extends PartUpgradeable implements IGrid public void onNeighborChanged() { this.updateState(); - if ( this.lastRedstone != this.host.hasRedstone( this.side ) ) + if( this.lastRedstone != this.host.hasRedstone( this.side ) ) { this.lastRedstone = !this.lastRedstone; - if ( this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE ) + if( this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE ) this.doBusWork(); } } diff --git a/src/main/java/appeng/parts/automation/PartUpgradeable.java b/src/main/java/appeng/parts/automation/PartUpgradeable.java index df1ca3568..4834948e9 100644 --- a/src/main/java/appeng/parts/automation/PartUpgradeable.java +++ b/src/main/java/appeng/parts/automation/PartUpgradeable.java @@ -52,6 +52,64 @@ public abstract class PartUpgradeable extends PartBasicState implements IAEAppEn return 4; } + @Override + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) + { + + } + + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) + { + if( inv == this.upgrades ) + { + this.upgradesChanged(); + } + } + + public void upgradesChanged() + { + + } + + protected boolean isSleeping() + { + if( this.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ) + { + switch( this.getRSMode() ) + { + case IGNORE: + return false; + + case HIGH_SIGNAL: + if( this.host.hasRedstone( this.side ) ) + return false; + + break; + + case LOW_SIGNAL: + if( !this.host.hasRedstone( this.side ) ) + return false; + + break; + + case SIGNAL_PULSE: + default: + break; + } + + return true; + } + + return false; + } + + @Override + public int getInstalledUpgrades( Upgrades u ) + { + return this.upgrades.getInstalledUpgrades( u ); + } + @Override public boolean canConnectRedstone() { @@ -77,8 +135,8 @@ public abstract class PartUpgradeable extends PartBasicState implements IAEAppEn @Override public void getDrops( List drops, boolean wrenched ) { - for ( ItemStack is : this.upgrades ) - if ( is != null ) + for( ItemStack is : this.upgrades ) + if( is != null ) drops.add( is ); } @@ -91,70 +149,12 @@ public abstract class PartUpgradeable extends PartBasicState implements IAEAppEn @Override public IInventory getInventoryByName( String name ) { - if ( name.equals( "upgrades" ) ) + if( name.equals( "upgrades" ) ) return this.upgrades; return null; } - @Override - public int getInstalledUpgrades( Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) - { - - } - - @Override - public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) - { - if ( inv == this.upgrades ) - { - this.upgradesChanged(); - } - } - - public void upgradesChanged() - { - - } - - protected boolean isSleeping() - { - if ( this.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ) - { - switch ( this.getRSMode() ) - { - case IGNORE: - return false; - - case HIGH_SIGNAL: - if ( this.host.hasRedstone( this.side ) ) - return false; - - break; - - case LOW_SIGNAL: - if ( !this.host.hasRedstone( this.side ) ) - return false; - - break; - - case SIGNAL_PULSE: - default: - break; - } - - return true; - } - - return false; - } - public RedstoneMode getRSMode() { return null; diff --git a/src/main/java/appeng/parts/automation/StackUpgradeInventory.java b/src/main/java/appeng/parts/automation/StackUpgradeInventory.java index 5cdd0cbba..745161f04 100644 --- a/src/main/java/appeng/parts/automation/StackUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/StackUpgradeInventory.java @@ -18,14 +18,13 @@ public class StackUpgradeInventory extends UpgradeInventory this.stack = stack; } - public int getMaxInstalled( Upgrades upgrades ) { int max = 0; - for ( ItemStack is : upgrades.getSupported().keySet() ) + for( ItemStack is : upgrades.getSupported().keySet() ) { - if ( Platform.isSameItem( this.stack, is ) ) + if( Platform.isSameItem( this.stack, is ) ) { max = upgrades.getSupported().get( is ); break; diff --git a/src/main/java/appeng/parts/automation/UpgradeInventory.java b/src/main/java/appeng/parts/automation/UpgradeInventory.java index 793fc4f25..954307d52 100644 --- a/src/main/java/appeng/parts/automation/UpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/UpgradeInventory.java @@ -66,13 +66,13 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement @Override public boolean isItemValidForSlot( int i, ItemStack itemstack ) { - if ( itemstack == null ) + if( itemstack == null ) return false; Item it = itemstack.getItem(); - if ( it instanceof IUpgradeModule ) + if( it instanceof IUpgradeModule ) { Upgrades u = ( (IUpgradeModule) it ).getType( itemstack ); - if ( u != null ) + if( u != null ) { return this.getInstalledUpgrades( u ) < this.getMaxInstalled( u ); } @@ -82,10 +82,10 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement public int getInstalledUpgrades( Upgrades u ) { - if ( !this.cached ) + if( !this.cached ) this.updateUpgradeInfo(); - switch ( u ) + switch( u ) { case CAPACITY: return this.capacityUpgrades; @@ -111,13 +111,13 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement this.cached = true; this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0; - for ( ItemStack is : this ) + for( ItemStack is : this ) { - if ( is == null || is.getItem() == null || !( is.getItem() instanceof IUpgradeModule ) ) + if( is == null || is.getItem() == null || !( is.getItem() instanceof IUpgradeModule ) ) continue; Upgrades myUpgrade = ( (IUpgradeModule) is.getItem() ).getType( is ); - switch ( myUpgrade ) + switch( myUpgrade ) { case CAPACITY: this.capacityUpgrades++; @@ -167,7 +167,7 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) { this.cached = false; - if ( this.parent != null && Platform.isServer() ) + if( this.parent != null && Platform.isServer() ) this.parent.onChangeInventory( inv, slot, mc, removedStack, newStack ); } } diff --git a/src/main/java/appeng/parts/layers/InvLayerData.java b/src/main/java/appeng/parts/layers/InvLayerData.java index 1afd1291c..adf87f5cd 100644 --- a/src/main/java/appeng/parts/layers/InvLayerData.java +++ b/src/main/java/appeng/parts/layers/InvLayerData.java @@ -18,12 +18,14 @@ package appeng.parts.layers; + import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; + public class InvLayerData { @@ -35,72 +37,74 @@ public class InvLayerData final private List inventories; final private List slots; - public InvLayerData( int[][] a, List b, List c) { + public InvLayerData( int[][] a, List b, List c ) + { this.sides = a; this.inventories = b; this.slots = c; } + public ItemStack decreaseStackSize( int slot, int amount ) + { + if( this.isSlotValid( slot ) ) + return this.slots.get( slot ).decreaseStackSize( amount ); + + return null; + } + /** * check if a slot index is valid, prevent crashes from bad code :) * * @param slot slot index + * * @return true, if the slot exists. */ - boolean isSlotValid(int slot) + boolean isSlotValid( int slot ) { return this.slots != null && slot >= 0 && slot < this.slots.size(); } - public ItemStack decreaseStackSize(int slot, int amount) - { - if ( this.isSlotValid( slot ) ) - return this.slots.get( slot ).decreaseStackSize( amount ); - - return null; - } - public int getSizeInventory() { - if ( this.slots == null ) + if( this.slots == null ) return 0; return this.slots.size(); } - public ItemStack getStackInSlot(int slot) + public ItemStack getStackInSlot( int slot ) { - if ( this.isSlotValid( slot ) ) + if( this.isSlotValid( slot ) ) return this.slots.get( slot ).getStackInSlot(); return null; } - public boolean isItemValidForSlot(int slot, ItemStack itemstack) + public boolean isItemValidForSlot( int slot, ItemStack itemstack ) { - if ( this.isSlotValid( slot ) ) + if( this.isSlotValid( slot ) ) return this.slots.get( slot ).isItemValidForSlot( itemstack ); return false; } - public void setInventorySlotContents(int slot, ItemStack itemstack) + public void setInventorySlotContents( int slot, ItemStack itemstack ) { - if ( this.isSlotValid( slot ) ) + if( this.isSlotValid( slot ) ) this.slots.get( slot ).setInventorySlotContents( itemstack ); } - public boolean canExtractItem(int slot, ItemStack itemstack, int side) + public boolean canExtractItem( int slot, ItemStack itemstack, int side ) { - if ( this.isSlotValid( slot ) ) + if( this.isSlotValid( slot ) ) return this.slots.get( slot ).canExtractItem( itemstack, side ); return false; } - public boolean canInsertItem(int slot, ItemStack itemstack, int side) + public boolean canInsertItem( int slot, ItemStack itemstack, int side ) { - if ( this.isSlotValid( slot ) ) + if( this.isSlotValid( slot ) ) return this.slots.get( slot ).canInsertItem( itemstack, side ); return false; @@ -108,18 +112,17 @@ public class InvLayerData public void markDirty() { - if ( this.inventories != null ) + if( this.inventories != null ) { - for (IInventory inv : this.inventories) + for( IInventory inv : this.inventories ) inv.markDirty(); } } - public int[] getAccessibleSlotsFromSide(int side) + public int[] getAccessibleSlotsFromSide( int side ) { - if ( this.sides == null || side < 0 || side > 5 ) + if( this.sides == null || side < 0 || side > 5 ) return NULL_SIDES; return this.sides[side]; } - } diff --git a/src/main/java/appeng/parts/layers/InvSot.java b/src/main/java/appeng/parts/layers/InvSot.java index b335870cf..83872574e 100644 --- a/src/main/java/appeng/parts/layers/InvSot.java +++ b/src/main/java/appeng/parts/layers/InvSot.java @@ -18,21 +18,24 @@ package appeng.parts.layers; + import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; + public class InvSot { final public ISidedInventory partInv; final public int index; - public InvSot(ISidedInventory part, int slot) { + public InvSot( ISidedInventory part, int slot ) + { this.partInv = part; this.index = slot; } - public ItemStack decreaseStackSize(int j) + public ItemStack decreaseStackSize( int j ) { return this.partInv.decrStackSize( this.index, j ); } @@ -42,24 +45,23 @@ public class InvSot return this.partInv.getStackInSlot( this.index ); } - public boolean isItemValidForSlot(ItemStack itemstack) + public boolean isItemValidForSlot( ItemStack itemstack ) { return this.partInv.isItemValidForSlot( this.index, itemstack ); } - public void setInventorySlotContents(ItemStack itemstack) + public void setInventorySlotContents( ItemStack itemstack ) { this.partInv.setInventorySlotContents( this.index, itemstack ); } - public boolean canExtractItem(ItemStack itemstack, int side) + public boolean canExtractItem( ItemStack itemstack, int side ) { return this.partInv.canExtractItem( this.index, itemstack, side ); } - public boolean canInsertItem(ItemStack itemstack, int side) + public boolean canInsertItem( ItemStack itemstack, int side ) { return this.partInv.canInsertItem( this.index, itemstack, side ); } - } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java b/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java index ab7c38553..7f1d3c73d 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java @@ -18,6 +18,7 @@ package appeng.parts.layers; + import net.minecraftforge.common.util.ForgeDirection; import cofh.api.energy.IEnergyConnection; @@ -33,53 +34,52 @@ public class LayerIEnergyHandler extends LayerBase implements IEnergyHandler { @Override - public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) + public int receiveEnergy( ForgeDirection from, int maxReceive, boolean simulate ) { IPart part = this.getPart( from ); - if ( part instanceof IEnergyReceiver ) - return ((IEnergyReceiver) part).receiveEnergy( from, maxReceive, simulate ); + if( part instanceof IEnergyReceiver ) + return ( (IEnergyReceiver) part ).receiveEnergy( from, maxReceive, simulate ); return 0; } @Override - public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) + public int extractEnergy( ForgeDirection from, int maxExtract, boolean simulate ) { IPart part = this.getPart( from ); - if ( part instanceof IEnergyProvider ) - return ((IEnergyProvider) part).extractEnergy( from, maxExtract, simulate ); + if( part instanceof IEnergyProvider ) + return ( (IEnergyProvider) part ).extractEnergy( from, maxExtract, simulate ); return 0; } @Override - public int getEnergyStored(ForgeDirection from) + public int getEnergyStored( ForgeDirection from ) { IPart part = this.getPart( from ); - if ( part instanceof IEnergyProvider ) - return ((IEnergyProvider) part).getEnergyStored( from ); + if( part instanceof IEnergyProvider ) + return ( (IEnergyProvider) part ).getEnergyStored( from ); return 0; } @Override - public int getMaxEnergyStored(ForgeDirection from) + public int getMaxEnergyStored( ForgeDirection from ) { IPart part = this.getPart( from ); - if ( part instanceof IEnergyProvider ) - return ((IEnergyProvider) part).getMaxEnergyStored( from ); + if( part instanceof IEnergyProvider ) + return ( (IEnergyProvider) part ).getMaxEnergyStored( from ); return 0; } @Override - public boolean canConnectEnergy(ForgeDirection from) + public boolean canConnectEnergy( ForgeDirection from ) { IPart part = this.getPart( from ); - if ( part instanceof IEnergyConnection ) - return ((IEnergyConnection) part).canConnectEnergy( from ); + if( part instanceof IEnergyConnection ) + return ( (IEnergyConnection) part ).canConnectEnergy( from ); return false; } - } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergySink.java b/src/main/java/appeng/parts/layers/LayerIEnergySink.java index 7ffa10e72..03867ae51 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergySink.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergySink.java @@ -18,6 +18,7 @@ package appeng.parts.layers; + import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; @@ -32,14 +33,10 @@ import appeng.api.parts.LayerBase; import appeng.api.parts.LayerFlags; import appeng.util.Platform; + public class LayerIEnergySink extends LayerBase implements IEnergySink { - private boolean isInIC2() - { - return this.getLayerFlags().contains( LayerFlags.IC2_ENET ); - } - private TileEntity getEnergySinkTile() { IPartHost host = (IPartHost) this; @@ -48,7 +45,7 @@ public class LayerIEnergySink extends LayerBase implements IEnergySink private World getEnergySinkWorld() { - if ( this.getEnergySinkTile() == null ) + if( this.getEnergySinkTile() == null ) return null; return this.getEnergySinkTile().getWorldObj(); @@ -58,7 +55,7 @@ public class LayerIEnergySink extends LayerBase implements IEnergySink { TileEntity te = this.getEnergySinkTile(); - if ( te == null ) + if( te == null ) return false; return !te.isInvalid() && te.getWorldObj().blockExists( te.xCoord, te.yCoord, te.zCoord ); @@ -66,13 +63,13 @@ public class LayerIEnergySink extends LayerBase implements IEnergySink private void addToENet() { - if ( this.getEnergySinkWorld() == null ) + if( this.getEnergySinkWorld() == null ) return; // re-add this.removeFromENet(); - if ( !this.isInIC2() && Platform.isServer() && this.isTileValid() ) + if( !this.isInIC2() && Platform.isServer() && this.isTileValid() ) { this.getLayerFlags().add( LayerFlags.IC2_ENET ); MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergySink) this.getEnergySinkTile() ) ); @@ -81,10 +78,10 @@ public class LayerIEnergySink extends LayerBase implements IEnergySink private void removeFromENet() { - if ( this.getEnergySinkWorld() == null ) + if( this.getEnergySinkWorld() == null ) return; - if ( this.isInIC2() && Platform.isServer() ) + if( this.isInIC2() && Platform.isServer() ) { this.getLayerFlags().remove( LayerFlags.IC2_ENET ); MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergySink) this.getEnergySinkTile() ) ); @@ -93,14 +90,14 @@ public class LayerIEnergySink extends LayerBase implements IEnergySink private boolean interestedInIC2() { - if ( !((IPartHost) this).isInWorld() ) + if( !( (IPartHost) this ).isInWorld() ) return false; int interested = 0; - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) { IPart part = this.getPart( dir ); - if ( part instanceof IEnergyTile ) + if( part instanceof IEnergyTile ) { interested++; } @@ -113,67 +110,71 @@ public class LayerIEnergySink extends LayerBase implements IEnergySink { super.partChanged(); - if ( this.interestedInIC2() ) + if( this.interestedInIC2() ) this.addToENet(); else this.removeFromENet(); } @Override - public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + public boolean acceptsEnergyFrom( TileEntity emitter, ForgeDirection direction ) { - if ( !this.isInIC2() ) + if( !this.isInIC2() ) return false; IPart part = this.getPart( direction ); - if ( part instanceof IEnergySink ) - return ((IEnergySink) part).acceptsEnergyFrom( emitter, direction ); + if( part instanceof IEnergySink ) + return ( (IEnergySink) part ).acceptsEnergyFrom( emitter, direction ); return false; } + private boolean isInIC2() + { + return this.getLayerFlags().contains( LayerFlags.IC2_ENET ); + } + @Override public double getDemandedEnergy() { - if ( !this.isInIC2() ) + if( !this.isInIC2() ) return 0; // this is a flawed implementation, that requires a change to the IC2 API. - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) { IPart part = this.getPart( dir ); - if ( part instanceof IEnergySink ) + if( part instanceof IEnergySink ) { // use lower number cause ic2 deletes power it sends that isn't received. - return ((IEnergySink) part).getDemandedEnergy(); + return ( (IEnergySink) part ).getDemandedEnergy(); } } return 0; } - @Override - public double injectEnergy(ForgeDirection directionFrom, double amount, double voltage) - { - if ( !this.isInIC2() ) - return amount; - - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) - { - IPart part = this.getPart( dir ); - if ( part instanceof IEnergySink ) - { - return ((IEnergySink) part).injectEnergy( directionFrom, amount, voltage ); - } - } - - return amount; - } - @Override public int getSinkTier() { return Integer.MAX_VALUE; // no real options here... } + @Override + public double injectEnergy( ForgeDirection directionFrom, double amount, double voltage ) + { + if( !this.isInIC2() ) + return amount; + + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) + { + IPart part = this.getPart( dir ); + if( part instanceof IEnergySink ) + { + return ( (IEnergySink) part ).injectEnergy( directionFrom, amount, voltage ); + } + } + + return amount; + } } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergySource.java b/src/main/java/appeng/parts/layers/LayerIEnergySource.java index cc877902f..ad76f01c3 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergySource.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergySource.java @@ -18,6 +18,7 @@ package appeng.parts.layers; + import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; @@ -34,14 +35,10 @@ import appeng.api.parts.LayerBase; import appeng.api.parts.LayerFlags; import appeng.util.Platform; + public class LayerIEnergySource extends LayerBase implements IEnergySource { - private boolean isInIC2() - { - return this.getLayerFlags().contains( LayerFlags.IC2_ENET ); - } - private TileEntity getEnergySourceTile() { IPartHost host = (IPartHost) this; @@ -50,7 +47,7 @@ public class LayerIEnergySource extends LayerBase implements IEnergySource private World getEnergySourceWorld() { - if ( this.getEnergySourceTile() == null ) + if( this.getEnergySourceTile() == null ) return null; return this.getEnergySourceTile().getWorldObj(); } @@ -58,20 +55,20 @@ public class LayerIEnergySource extends LayerBase implements IEnergySource private boolean isTileValid() { TileEntity te = this.getEnergySourceTile(); - if ( te == null ) + if( te == null ) return false; return !te.isInvalid(); } private void addToENet() { - if ( this.getEnergySourceWorld() == null ) + if( this.getEnergySourceWorld() == null ) return; // re-add this.removeFromENet(); - if ( !this.isInIC2() && Platform.isServer() && this.isTileValid() ) + if( !this.isInIC2() && Platform.isServer() && this.isTileValid() ) { this.getLayerFlags().add( LayerFlags.IC2_ENET ); MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergySink) this.getEnergySourceTile() ) ); @@ -80,10 +77,10 @@ public class LayerIEnergySource extends LayerBase implements IEnergySource private void removeFromENet() { - if ( this.getEnergySourceWorld() == null ) + if( this.getEnergySourceWorld() == null ) return; - if ( this.isInIC2() && Platform.isServer() ) + if( this.isInIC2() && Platform.isServer() ) { this.getLayerFlags().remove( LayerFlags.IC2_ENET ); MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergySink) this.getEnergySourceTile() ) ); @@ -92,14 +89,14 @@ public class LayerIEnergySource extends LayerBase implements IEnergySource private boolean interestedInIC2() { - if ( !((IPartHost) this).isInWorld() ) + if( !( (IPartHost) this ).isInWorld() ) return false; int interested = 0; - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) { IPart part = this.getPart( dir ); - if ( part instanceof IEnergyTile ) + if( part instanceof IEnergyTile ) { interested++; } @@ -112,39 +109,44 @@ public class LayerIEnergySource extends LayerBase implements IEnergySource { super.partChanged(); - if ( this.interestedInIC2() ) + if( this.interestedInIC2() ) this.addToENet(); else this.removeFromENet(); } @Override - public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction) + public boolean emitsEnergyTo( TileEntity receiver, ForgeDirection direction ) { - if ( !this.isInIC2() ) + if( !this.isInIC2() ) return false; IPart part = this.getPart( direction ); - if ( part instanceof IEnergySink ) - return ((IEnergyEmitter) part).emitsEnergyTo( receiver, direction ); + if( part instanceof IEnergySink ) + return ( (IEnergyEmitter) part ).emitsEnergyTo( receiver, direction ); return false; } + private boolean isInIC2() + { + return this.getLayerFlags().contains( LayerFlags.IC2_ENET ); + } + @Override public double getOfferedEnergy() { - if ( !this.isInIC2() ) + if( !this.isInIC2() ) return 0; // this is a flawed implementation, that requires a change to the IC2 API. - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) { IPart part = this.getPart( dir ); - if ( part instanceof IEnergySource ) + if( part instanceof IEnergySource ) { // use lower number cause ic2 deletes power it sends that isn't received. - return ((IEnergySource) part).getOfferedEnergy(); + return ( (IEnergySource) part ).getOfferedEnergy(); } } @@ -152,16 +154,16 @@ public class LayerIEnergySource extends LayerBase implements IEnergySource } @Override - public void drawEnergy(double amount) + public void drawEnergy( double amount ) { // this is a flawed implementation, that requires a change to the IC2 API. - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) { IPart part = this.getPart( dir ); - if ( part instanceof IEnergySource ) + if( part instanceof IEnergySource ) { - ((IEnergySource) part).drawEnergy( amount ); + ( (IEnergySource) part ).drawEnergy( amount ); return; } } @@ -172,16 +174,15 @@ public class LayerIEnergySource extends LayerBase implements IEnergySource { // this is a flawed implementation, that requires a change to the IC2 API. - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) { IPart part = this.getPart( dir ); - if ( part instanceof IEnergySource ) + if( part instanceof IEnergySource ) { - return ((IEnergySource) part).getSourceTier(); + return ( (IEnergySource) part ).getSourceTier(); } } return 0; } - } diff --git a/src/main/java/appeng/parts/layers/LayerIFluidHandler.java b/src/main/java/appeng/parts/layers/LayerIFluidHandler.java index acb614d56..6ea619089 100644 --- a/src/main/java/appeng/parts/layers/LayerIFluidHandler.java +++ b/src/main/java/appeng/parts/layers/LayerIFluidHandler.java @@ -18,6 +18,7 @@ package appeng.parts.layers; + import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; @@ -26,63 +27,63 @@ import net.minecraftforge.fluids.IFluidHandler; import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; + public class LayerIFluidHandler extends LayerBase implements IFluidHandler { static final FluidTankInfo[] EMPTY_LIST = new FluidTankInfo[0]; @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) + public int fill( ForgeDirection from, FluidStack resource, boolean doFill ) { IPart part = this.getPart( from ); - if ( part instanceof IFluidHandler ) - return ((IFluidHandler) part).fill( from, resource, doFill ); + if( part instanceof IFluidHandler ) + return ( (IFluidHandler) part ).fill( from, resource, doFill ); return 0; } @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) + public FluidStack drain( ForgeDirection from, FluidStack resource, boolean doDrain ) { IPart part = this.getPart( from ); - if ( part instanceof IFluidHandler ) - return ((IFluidHandler) part).drain( from, resource, doDrain ); + if( part instanceof IFluidHandler ) + return ( (IFluidHandler) part ).drain( from, resource, doDrain ); return null; } @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) + public FluidStack drain( ForgeDirection from, int maxDrain, boolean doDrain ) { IPart part = this.getPart( from ); - if ( part instanceof IFluidHandler ) - return ((IFluidHandler) part).drain( from, maxDrain, doDrain ); + if( part instanceof IFluidHandler ) + return ( (IFluidHandler) part ).drain( from, maxDrain, doDrain ); return null; } @Override - public boolean canFill(ForgeDirection from, net.minecraftforge.fluids.Fluid fluid) + public boolean canFill( ForgeDirection from, net.minecraftforge.fluids.Fluid fluid ) { IPart part = this.getPart( from ); - if ( part instanceof IFluidHandler ) - return ((IFluidHandler) part).canFill( from, fluid ); + if( part instanceof IFluidHandler ) + return ( (IFluidHandler) part ).canFill( from, fluid ); return false; } @Override - public boolean canDrain(ForgeDirection from, net.minecraftforge.fluids.Fluid fluid) + public boolean canDrain( ForgeDirection from, net.minecraftforge.fluids.Fluid fluid ) { IPart part = this.getPart( from ); - if ( part instanceof IFluidHandler ) - return ((IFluidHandler) part).canDrain( from, fluid ); + if( part instanceof IFluidHandler ) + return ( (IFluidHandler) part ).canDrain( from, fluid ); return false; } @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) + public FluidTankInfo[] getTankInfo( ForgeDirection from ) { IPart part = this.getPart( from ); - if ( part instanceof IFluidHandler ) - return ((IFluidHandler) part).getTankInfo( from ); + if( part instanceof IFluidHandler ) + return ( (IFluidHandler) part ).getTankInfo( from ); return EMPTY_LIST; } - } diff --git a/src/main/java/appeng/parts/layers/LayerIPipeConnection.java b/src/main/java/appeng/parts/layers/LayerIPipeConnection.java index 65c89dfd2..4d11c8d5c 100644 --- a/src/main/java/appeng/parts/layers/LayerIPipeConnection.java +++ b/src/main/java/appeng/parts/layers/LayerIPipeConnection.java @@ -18,6 +18,7 @@ package appeng.parts.layers; + import net.minecraftforge.common.util.ForgeDirection; import buildcraft.api.transport.IPipeConnection; @@ -26,16 +27,16 @@ import buildcraft.api.transport.IPipeTile.PipeType; import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; + public class LayerIPipeConnection extends LayerBase implements IPipeConnection { @Override - public ConnectOverride overridePipeConnection(PipeType type, ForgeDirection with) + public ConnectOverride overridePipeConnection( PipeType type, ForgeDirection with ) { IPart part = this.getPart( with ); - if ( part instanceof IPipeConnection ) - return ((IPipeConnection) part).overridePipeConnection( type, with ); + if( part instanceof IPipeConnection ) + return ( (IPipeConnection) part ).overridePipeConnection( type, with ); return ConnectOverride.DEFAULT; } - } diff --git a/src/main/java/appeng/parts/layers/LayerISidedInventory.java b/src/main/java/appeng/parts/layers/LayerISidedInventory.java index 903510608..de5a17cac 100644 --- a/src/main/java/appeng/parts/layers/LayerISidedInventory.java +++ b/src/main/java/appeng/parts/layers/LayerISidedInventory.java @@ -18,6 +18,7 @@ package appeng.parts.layers; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -32,6 +33,7 @@ import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.LayerBase; + /** * Inventory wrapper for parts, * @@ -64,10 +66,10 @@ public class LayerISidedInventory extends LayerBase implements ISidedInventory inventories = new ArrayList(); int slotCount = 0; - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) { IPart bp = this.getPart( side ); - if ( bp instanceof ISidedInventory ) + if( bp instanceof ISidedInventory ) { ISidedInventory part = (ISidedInventory) bp; slotCount += part.getSizeInventory(); @@ -75,7 +77,7 @@ public class LayerISidedInventory extends LayerBase implements ISidedInventory } } - if ( inventories.isEmpty() || slotCount == 0 ) + if( inventories.isEmpty() || slotCount == 0 ) { inventories = null; } @@ -86,21 +88,21 @@ public class LayerISidedInventory extends LayerBase implements ISidedInventory int offsetForLayer = 0; int offsetForPart = 0; - for (ISidedInventory sides : inventories) + for( ISidedInventory sides : inventories ) { offsetForPart = 0; slotCount = sides.getSizeInventory(); ForgeDirection currentSide = ForgeDirection.UNKNOWN; - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) - if ( this.getPart( side ) == sides ) + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) + if( this.getPart( side ) == sides ) { currentSide = side; break; } int[] cSidesList = sideData[currentSide.ordinal()] = new int[slotCount]; - for (int cSlot = 0; cSlot < slotCount; cSlot++) + for( int cSlot = 0; cSlot < slotCount; cSlot++ ) { cSidesList[cSlot] = offsetForLayer; slots.set( offsetForLayer, new InvSot( sides, offsetForPart ) ); @@ -110,7 +112,7 @@ public class LayerISidedInventory extends LayerBase implements ISidedInventory } } - if ( sideData == null || slots == null ) + if( sideData == null || slots == null ) this.invLayer = null; else this.invLayer = new InvLayerData( sideData, inventories, slots ); @@ -119,93 +121,48 @@ public class LayerISidedInventory extends LayerBase implements ISidedInventory super.notifyNeighbors(); } - @Override - public ItemStack decrStackSize(int slot, int amount) - { - if ( this.invLayer == null ) - return null; - - return this.invLayer.decreaseStackSize( slot, amount ); - } - @Override public int getSizeInventory() { - if ( this.invLayer == null ) + if( this.invLayer == null ) return 0; return this.invLayer.getSizeInventory(); } @Override - public ItemStack getStackInSlot(int slot) + public ItemStack getStackInSlot( int slot ) { - if ( this.invLayer == null ) + if( this.invLayer == null ) return null; return this.invLayer.getStackInSlot( slot ); } @Override - public boolean isItemValidForSlot(int slot, ItemStack itemstack) + public ItemStack decrStackSize( int slot, int amount ) { - if ( this.invLayer == null ) - return false; + if( this.invLayer == null ) + return null; - return this.invLayer.isItemValidForSlot( slot, itemstack ); + return this.invLayer.decreaseStackSize( slot, amount ); } @Override - public void setInventorySlotContents(int slot, ItemStack itemstack) + public ItemStack getStackInSlotOnClosing( int slot ) { - if ( this.invLayer == null ) + return null; + } + + @Override + public void setInventorySlotContents( int slot, ItemStack itemstack ) + { + if( this.invLayer == null ) return; this.invLayer.setInventorySlotContents( slot, itemstack ); } - @Override - public boolean canExtractItem(int slot, ItemStack itemstack, int side) - { - if ( this.invLayer == null ) - return false; - - return this.invLayer.canExtractItem( slot, itemstack, side ); - } - - @Override - public boolean canInsertItem(int slot, ItemStack itemstack, int side) - { - if ( this.invLayer == null ) - return false; - - return this.invLayer.canInsertItem( slot, itemstack, side ); - } - - @Override - public void markDirty() - { - if ( this.invLayer != null ) - this.invLayer.markDirty(); - - super.markForSave(); - } - - @Override - public int[] getAccessibleSlotsFromSide(int side) - { - if ( this.invLayer != null ) - return this.invLayer.getAccessibleSlotsFromSide( side ); - - return NULL_SIDES; - } - - @Override - public int getInventoryStackLimit() - { - return 64; // no options here. - } - @Override public String getInventoryName() { @@ -219,24 +176,69 @@ public class LayerISidedInventory extends LayerBase implements ISidedInventory } @Override - public ItemStack getStackInSlotOnClosing(int slot) + public int getInventoryStackLimit() { - return null; + return 64; // no options here. } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) + public boolean isUseableByPlayer( EntityPlayer entityplayer ) { return false; } + @Override + public void openInventory() + { + } + @Override public void closeInventory() { } @Override - public void openInventory() + public boolean isItemValidForSlot( int slot, ItemStack itemstack ) { + if( this.invLayer == null ) + return false; + + return this.invLayer.isItemValidForSlot( slot, itemstack ); + } + + @Override + public void markDirty() + { + if( this.invLayer != null ) + this.invLayer.markDirty(); + + super.markForSave(); + } + + @Override + public int[] getAccessibleSlotsFromSide( int side ) + { + if( this.invLayer != null ) + return this.invLayer.getAccessibleSlotsFromSide( side ); + + return NULL_SIDES; + } + + @Override + public boolean canInsertItem( int slot, ItemStack itemstack, int side ) + { + if( this.invLayer == null ) + return false; + + return this.invLayer.canInsertItem( slot, itemstack, side ); + } + + @Override + public boolean canExtractItem( int slot, ItemStack itemstack, int side ) + { + if( this.invLayer == null ) + return false; + + return this.invLayer.canExtractItem( slot, itemstack, side ); } } diff --git a/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java b/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java index c15518f4d..691b1e29b 100644 --- a/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java +++ b/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java @@ -18,6 +18,7 @@ package appeng.parts.layers; + import net.minecraftforge.common.util.ForgeDirection; import appeng.api.implementations.tiles.ITileStorageMonitorable; @@ -26,16 +27,16 @@ import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import appeng.api.storage.IStorageMonitorable; + public class LayerITileStorageMonitorable extends LayerBase implements ITileStorageMonitorable { @Override - public IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src) + public IStorageMonitorable getMonitorable( ForgeDirection side, BaseActionSource src ) { IPart part = this.getPart( side ); - if ( part instanceof ITileStorageMonitorable ) - return ((ITileStorageMonitorable) part).getMonitorable( side, src ); + if( part instanceof ITileStorageMonitorable ) + return ( (ITileStorageMonitorable) part ).getMonitorable( side, src ); return null; } - } diff --git a/src/main/java/appeng/parts/misc/PartCableAnchor.java b/src/main/java/appeng/parts/misc/PartCableAnchor.java index 13154cfa7..b82c71508 100644 --- a/src/main/java/appeng/parts/misc/PartCableAnchor.java +++ b/src/main/java/appeng/parts/misc/PartCableAnchor.java @@ -18,6 +18,7 @@ package appeng.parts.misc; + import java.io.IOException; import java.util.List; import java.util.Random; @@ -48,6 +49,7 @@ import appeng.api.parts.IPartRenderHelper; import appeng.api.parts.ISimplifiedBundle; import appeng.api.parts.PartItemStack; + public class PartCableAnchor implements IPart { @@ -56,35 +58,29 @@ public class PartCableAnchor implements IPart IPartHost host = null; ForgeDirection mySide = ForgeDirection.UP; - public PartCableAnchor(ItemStack is) { + public PartCableAnchor( ItemStack is ) + { this.is = is; } @Override - @SideOnly(Side.CLIENT) - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) + public void getBoxes( IPartCollisionHelper bch ) { - this.renderCache = rh.useSimplifiedRendering( x, y, z, this, this.renderCache ); - IIcon myIcon = this.is.getIconIndex(); - rh.setTexture( myIcon ); - if ( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) - rh.setBounds( 7, 7, 10, 9, 9, 14 ); + if( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) + bch.addBox( 7, 7, 10, 9, 9, 14 ); else - rh.setBounds( 7, 7, 10, 9, 9, 16 ); - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( null ); + bch.addBox( 7, 7, 10, 9, 9, 16 ); } @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World world, int x, int y, int z, Random r) + public ItemStack getItemStack( PartItemStack wrenched ) { - + return this.is; } @Override - @SideOnly(Side.CLIENT) - public void renderInventory(IPartRenderHelper instance, RenderBlocks renderer) + @SideOnly( Side.CLIENT ) + public void renderInventory( IPartRenderHelper instance, RenderBlocks renderer ) { instance.setTexture( this.is.getIconIndex() ); instance.setBounds( 7, 7, 4, 9, 9, 14 ); @@ -93,18 +89,31 @@ public class PartCableAnchor implements IPart } @Override - public void getBoxes(IPartCollisionHelper bch) + @SideOnly( Side.CLIENT ) + public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) { - if ( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) - bch.addBox( 7, 7, 10, 9, 9, 14 ); + this.renderCache = rh.useSimplifiedRendering( x, y, z, this, this.renderCache ); + IIcon myIcon = this.is.getIconIndex(); + rh.setTexture( myIcon ); + if( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) + rh.setBounds( 7, 7, 10, 9, 9, 14 ); else - bch.addBox( 7, 7, 10, 9, 9, 16 ); + rh.setBounds( 7, 7, 10, 9, 9, 16 ); + rh.renderBlock( x, y, z, renderer ); + rh.setTexture( null ); } @Override - public ItemStack getItemStack(PartItemStack wrenched) + @SideOnly( Side.CLIENT ) + public void renderDynamic( double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer ) { - return this.is; + + } + + @Override + public IIcon getBreakingTexture() + { + return null; } @Override @@ -113,13 +122,6 @@ public class PartCableAnchor implements IPart return false; } - @Override - @SideOnly(Side.CLIENT) - public void renderDynamic(double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer) - { - - } - @Override public boolean isSolid() { @@ -133,13 +135,13 @@ public class PartCableAnchor implements IPart } @Override - public void writeToNBT(NBTTagCompound data) + public void writeToNBT( NBTTagCompound data ) { } @Override - public void readFromNBT(NBTTagCompound data) + public void readFromNBT( NBTTagCompound data ) { } @@ -150,6 +152,12 @@ public class PartCableAnchor implements IPart return 0; } + @Override + public boolean isLadder( EntityLivingBase entity ) + { + return this.mySide.offsetY == 0 && ( entity.isCollidedHorizontally || !entity.onGround ); + } + @Override public void onNeighborChanged() { @@ -169,13 +177,13 @@ public class PartCableAnchor implements IPart } @Override - public void writeToStream(ByteBuf data) throws IOException + public void writeToStream( ByteBuf data ) throws IOException { } @Override - public boolean readFromStream(ByteBuf data) throws IOException + public boolean readFromStream( ByteBuf data ) throws IOException { return false; } @@ -187,7 +195,7 @@ public class PartCableAnchor implements IPart } @Override - public void onEntityCollision(Entity entity) + public void onEntityCollision( Entity entity ) { } @@ -211,20 +219,26 @@ public class PartCableAnchor implements IPart } @Override - public void setPartHostInfo(ForgeDirection side, IPartHost host, TileEntity tile) + public void setPartHostInfo( ForgeDirection side, IPartHost host, TileEntity tile ) { this.host = host; this.mySide = side; } @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) + public boolean onActivate( EntityPlayer player, Vec3 pos ) { return false; } @Override - public void getDrops(List drops, boolean wrenched) + public boolean onShiftActivate( EntityPlayer player, Vec3 pos ) + { + return false; + } + + @Override + public void getDrops( List drops, boolean wrenched ) { } @@ -236,32 +250,21 @@ public class PartCableAnchor implements IPart } @Override - public boolean isLadder(EntityLivingBase entity) - { - return this.mySide.offsetY == 0 && ( entity.isCollidedHorizontally || ! entity.onGround ); - } - - @Override - public boolean onShiftActivate(EntityPlayer player, Vec3 pos) - { - return false; - } - - @Override - public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) + @SideOnly( Side.CLIENT ) + public void randomDisplayTick( World world, int x, int y, int z, Random r ) { } @Override - public boolean canBePlacedOn(BusSupport what) + public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) + { + + } + + @Override + public boolean canBePlacedOn( BusSupport what ) { return what == BusSupport.CABLE || what == BusSupport.DENSE_CABLE; } - - @Override - public IIcon getBreakingTexture() - { - return null; - } } diff --git a/src/main/java/appeng/parts/misc/PartInterface.java b/src/main/java/appeng/parts/misc/PartInterface.java index 48af72277..64ee15911 100644 --- a/src/main/java/appeng/parts/misc/PartInterface.java +++ b/src/main/java/appeng/parts/misc/PartInterface.java @@ -73,8 +73,7 @@ import appeng.util.Platform; import appeng.util.inv.IInventoryDestination; -public class PartInterface extends PartBasicState - implements IGridTickable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, ISidedInventory, IAEAppEngInventory, ITileStorageMonitorable, IPriorityHost +public class PartInterface extends PartBasicState implements IGridTickable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, ISidedInventory, IAEAppEngInventory, ITileStorageMonitorable, IPriorityHost { final DualityInterface duality = new DualityInterface( this.proxy, this ); @@ -97,6 +96,19 @@ public class PartInterface extends PartBasicState this.duality.notifyNeighbors(); } + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 2, 2, 14, 14, 14, 16 ); + bch.addBox( 5, 5, 12, 11, 11, 14 ); + } + + @Override + public int getInstalledUpgrades( Upgrades u ) + { + return this.duality.getInstalledUpgrades( u ); + } + @Override @SideOnly( Side.CLIENT ) public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) @@ -113,6 +125,12 @@ public class PartInterface extends PartBasicState rh.renderInventoryBox( renderer ); } + @Override + public void gridChanged() + { + this.duality.gridChanged(); + } + @Override @SideOnly( Side.CLIENT ) public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) @@ -157,13 +175,6 @@ public class PartInterface extends PartBasicState this.duality.initialize(); } - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); - } - @Override public void getDrops( List drops, boolean wrenched ) { @@ -176,12 +187,6 @@ public class PartInterface extends PartBasicState return 4; } - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } - @Override public IConfigManager getConfigManager() { @@ -194,19 +199,13 @@ public class PartInterface extends PartBasicState return this.duality.getInventoryByName( name ); } - @Override - public int getInstalledUpgrades( Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } - @Override public boolean onPartActivate( EntityPlayer p, Vec3 pos ) { - if ( p.isSneaking() ) + if( p.isSneaking() ) return false; - if ( Platform.isServer() ) + if( Platform.isServer() ) Platform.openGUI( p, this.getTileEntity(), this.side, GuiBridge.GUI_INTERFACE ); return true; diff --git a/src/main/java/appeng/parts/misc/PartStorageBus.java b/src/main/java/appeng/parts/misc/PartStorageBus.java index 2e7c1efe4..067868960 100644 --- a/src/main/java/appeng/parts/misc/PartStorageBus.java +++ b/src/main/java/appeng/parts/misc/PartStorageBus.java @@ -91,8 +91,7 @@ import appeng.util.prioitylist.PrecisePriorityList; @Interface( iname = "BC", iface = "buildcraft.api.transport.IPipeConnection" ) -public class PartStorageBus extends PartUpgradeable - implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, IPipeConnection, IPriorityHost +public class PartStorageBus extends PartUpgradeable implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, IPipeConnection, IPriorityHost { final BaseActionSource mySrc; final AppEngInternalAEInventory Config = new AppEngInternalAEInventory( this, 63 ); @@ -124,7 +123,7 @@ public class PartStorageBus extends PartUpgradeable private void updateStatus() { boolean currentActive = this.proxy.isActive(); - if ( this.wasActive != currentActive ) + if( this.wasActive != currentActive ) { this.wasActive = currentActive; try @@ -132,7 +131,7 @@ public class PartStorageBus extends PartUpgradeable this.proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); this.host.markForUpdate(); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -152,11 +151,26 @@ public class PartStorageBus extends PartUpgradeable } @Override - public void writeToNBT( NBTTagCompound data ) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { - super.writeToNBT( data ); - this.Config.writeToNBT( data, "config" ); - data.setInteger( "priority", this.priority ); + this.resetCache( true ); + this.host.markForSave(); + } + + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) + { + super.onChangeInventory( inv, slot, mc, removedStack, newStack ); + + if( inv == this.Config ) + this.resetCache( true ); + } + + @Override + public void upgradesChanged() + { + super.upgradesChanged(); + this.resetCache( true ); } @Override @@ -167,36 +181,41 @@ public class PartStorageBus extends PartUpgradeable this.priority = data.getInteger( "priority" ); } + @Override + public void writeToNBT( NBTTagCompound data ) + { + super.writeToNBT( data ); + this.Config.writeToNBT( data, "config" ); + data.setInteger( "priority", this.priority ); + } + @Override public IInventory getInventoryByName( String name ) { - if ( name.equals( "config" ) ) + if( name.equals( "config" ) ) return this.Config; return super.getInventoryByName( name ); } - @Override - public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) + private void resetCache( boolean fullReset ) { - this.resetCache( true ); - this.host.markForSave(); - } + if( this.host == null || this.host.getTile() == null || this.host.getTile().getWorldObj() == null || this.host.getTile().getWorldObj().isRemote ) + return; - @Override - public void upgradesChanged() - { - super.upgradesChanged(); - this.resetCache( true ); - } + if( fullReset ) + this.resetCacheLogic = 2; + else + this.resetCacheLogic = 1; - @Override - public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) - { - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); - - if ( inv == this.Config ) - this.resetCache( true ); + try + { + this.proxy.getTick().alertDevice( this.proxy.getNode() ); + } + catch( GridAccessException e ) + { + // :P + } } @Override @@ -210,10 +229,10 @@ public class PartStorageBus extends PartUpgradeable { try { - if ( this.proxy.isActive() ) + if( this.proxy.isActive() ) this.proxy.getStorage().postAlterationOfStoredItems( StorageChannel.ITEMS, change, this.mySrc ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :( } @@ -225,6 +244,14 @@ public class PartStorageBus extends PartUpgradeable // not used here. } + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 3, 3, 15, 13, 13, 16 ); + bch.addBox( 2, 2, 14, 14, 14, 15 ); + bch.addBox( 5, 5, 12, 11, 11, 14 ); + } + @Override @SideOnly( Side.CLIENT ) public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) @@ -273,34 +300,6 @@ public class PartStorageBus extends PartUpgradeable this.resetCache( false ); } - private void resetCache( boolean fullReset ) - { - if ( this.host == null || this.host.getTile() == null || this.host.getTile().getWorldObj() == null || this.host.getTile().getWorldObj().isRemote ) - return; - - if ( fullReset ) - this.resetCacheLogic = 2; - else - this.resetCacheLogic = 1; - - try - { - this.proxy.getTick().alertDevice( this.proxy.getNode() ); - } - catch ( GridAccessException e ) - { - // :P - } - } - - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 3, 3, 15, 13, 13, 16 ); - bch.addBox( 2, 2, 14, 14, 14, 15 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); - } - @Override public int cableConnectionRenderTo() { @@ -310,9 +309,9 @@ public class PartStorageBus extends PartUpgradeable @Override public boolean onPartActivate( EntityPlayer player, Vec3 pos ) { - if ( !player.isSneaking() ) + if( !player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( player, this.getHost().getTile(), this.side, GuiBridge.GUI_STORAGEBUS ); @@ -331,10 +330,10 @@ public class PartStorageBus extends PartUpgradeable @Override public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) { - if ( this.resetCacheLogic != 0 ) + if( this.resetCacheLogic != 0 ) this.resetCache(); - if ( this.monitor != null ) + if( this.monitor != null ) return this.monitor.onTick(); return TickRateModulation.SLEEP; @@ -347,20 +346,20 @@ public class PartStorageBus extends PartUpgradeable IMEInventory in = this.getInternalHandler(); IItemList before = AEApi.instance().storage().createItemList(); - if ( in != null ) + if( in != null ) before = in.getAvailableItems( before ); this.cached = false; - if ( fullReset ) + if( fullReset ) this.handlerHash = 0; IMEInventory out = this.getInternalHandler(); - if ( this.monitor != null ) + if( this.monitor != null ) this.monitor.onTick(); IItemList after = AEApi.instance().storage().createItemList(); - if ( out != null ) + if( out != null ) after = out.getAvailableItems( after ); Platform.postListChanges( before, after, this, this.mySrc ); @@ -368,7 +367,7 @@ public class PartStorageBus extends PartUpgradeable public MEInventoryHandler getInternalHandler() { - if ( this.cached ) + if( this.cached ) return this.handler; boolean wasSleeping = this.monitor == null; @@ -379,7 +378,7 @@ public class PartStorageBus extends PartUpgradeable int newHandlerHash = Platform.generateTileHash( target ); - if ( this.handlerHash == newHandlerHash && this.handlerHash != 0 ) + if( this.handlerHash == newHandlerHash && this.handlerHash != 0 ) return this.handler; try @@ -387,7 +386,7 @@ public class PartStorageBus extends PartUpgradeable // force grid to update handlers... this.proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :3 } @@ -395,66 +394,66 @@ public class PartStorageBus extends PartUpgradeable this.handlerHash = newHandlerHash; this.handler = null; this.monitor = null; - if ( target != null ) + if( target != null ) { IExternalStorageHandler esh = AEApi.instance().registries().externalStorage().getHandler( target, this.side.getOpposite(), StorageChannel.ITEMS, this.mySrc ); - if ( esh != null ) + if( esh != null ) { IMEInventory inv = esh.getInventory( target, this.side.getOpposite(), StorageChannel.ITEMS, this.mySrc ); - if ( inv instanceof MEMonitorIInventory ) + if( inv instanceof MEMonitorIInventory ) { MEMonitorIInventory h = (MEMonitorIInventory) inv; h.mode = (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ); h.mySource = new MachineSource( this ); } - if ( inv instanceof MEMonitorIInventory ) + if( inv instanceof MEMonitorIInventory ) this.monitor = (MEMonitorIInventory) inv; - if ( inv != null ) + if( inv != null ) { this.checkInterfaceVsStorageBus( target, this.side.getOpposite() ); this.handler = new MEInventoryHandler( inv, StorageChannel.ITEMS ); - this.handler.setBaseAccess( ( AccessRestriction ) this.getConfigManager().getSetting( Settings.ACCESS ) ); + this.handler.setBaseAccess( (AccessRestriction) this.getConfigManager().getSetting( Settings.ACCESS ) ); this.handler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); this.handler.setPriority( this.priority ); IItemList priorityList = AEApi.instance().storage().createItemList(); int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for ( int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++ ) + for( int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++ ) { IAEItemStack is = this.Config.getAEStackInSlot( x ); - if ( is != null ) + if( is != null ) priorityList.add( is ); } - if ( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) + if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) this.handler.setPartitionList( new FuzzyPriorityList( priorityList, (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ) ) ); else this.handler.setPartitionList( new PrecisePriorityList( priorityList ) ); - if ( inv instanceof IMEMonitor ) + if( inv instanceof IMEMonitor ) ( (IMEMonitor) inv ).addListener( this, this.handler ); } } } // update sleep state... - if ( wasSleeping != ( this.monitor == null ) ) + if( wasSleeping != ( this.monitor == null ) ) { try { ITickManager tm = this.proxy.getTick(); - if ( this.monitor == null ) + if( this.monitor == null ) tm.sleepDevice( this.proxy.getNode() ); else tm.wakeDevice( this.proxy.getNode() ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :( } @@ -467,17 +466,17 @@ public class PartStorageBus extends PartUpgradeable { IInterfaceHost achievement = null; - if ( target instanceof IInterfaceHost ) + if( target instanceof IInterfaceHost ) achievement = (IInterfaceHost) target; - if ( target instanceof IPartHost ) + if( target instanceof IPartHost ) { Object part = ( (IPartHost) target ).getPart( side ); - if ( part instanceof IInterfaceHost ) + if( part instanceof IInterfaceHost ) achievement = (IInterfaceHost) part; } - if ( achievement != null && achievement.getActionableNode() != null ) + if( achievement != null && achievement.getActionableNode() != null ) { Platform.addStat( achievement.getActionableNode().getPlayerID(), Achievements.Recursive.getAchievement() ); // Platform.addStat( getActionableNode().getPlayerID(), Achievements.Recursive.getAchievement() ); @@ -487,13 +486,13 @@ public class PartStorageBus extends PartUpgradeable @Override public List getCellArray( StorageChannel channel ) { - if ( channel == StorageChannel.ITEMS ) + if( channel == StorageChannel.ITEMS ) { IMEInventoryHandler out = this.proxy.isActive() ? this.getInternalHandler() : null; - if ( out != null ) + if( out != null ) return Collections.singletonList( out ); } - return Arrays.asList( new IMEInventoryHandler[] { } ); + return Arrays.asList( new IMEInventoryHandler[] {} ); } @Override diff --git a/src/main/java/appeng/parts/misc/PartToggleBus.java b/src/main/java/appeng/parts/misc/PartToggleBus.java index e992adc5e..89c074cfa 100644 --- a/src/main/java/appeng/parts/misc/PartToggleBus.java +++ b/src/main/java/appeng/parts/misc/PartToggleBus.java @@ -93,6 +93,31 @@ public class PartToggleBus extends PartBasicState return this.is.getIconIndex(); } + @Override + public AECableType getCableConnectionType( ForgeDirection dir ) + { + return AECableType.GLASS; + } + + @Override + public void securityBreak() + { + if( this.is.stackSize > 0 ) + { + List items = new ArrayList(); + items.add( this.is.copy() ); + this.host.removePart( this.side, false ); + Platform.spawnDrops( this.tile.getWorldObj(), this.tile.xCoord, this.tile.yCoord, this.tile.zCoord, items ); + this.is.stackSize = 0; + } + } + + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 6, 6, 11, 10, 10, 16 ); + } + @Override @SideOnly( Side.CLIENT ) public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) @@ -145,7 +170,7 @@ public class PartToggleBus extends PartBasicState boolean oldHasRedstone = this.hasRedstone; this.hasRedstone = this.getHost().hasRedstone( this.side ); - if ( this.hasRedstone != oldHasRedstone ) + if( this.hasRedstone != oldHasRedstone ) { this.updateInternalState(); this.getHost().markForUpdate(); @@ -195,18 +220,6 @@ public class PartToggleBus extends PartBasicState return this.outerProxy.getNode(); } - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 11, 10, 10, 16 ); - } - - @Override - public AECableType getCableConnectionType( ForgeDirection dir ) - { - return AECableType.GLASS; - } - @Override public int cableConnectionRenderTo() { @@ -220,33 +233,20 @@ public class PartToggleBus extends PartBasicState this.outerProxy.setOwner( player ); } - @Override - public void securityBreak() - { - if ( this.is.stackSize > 0 ) - { - List items = new ArrayList(); - items.add( this.is.copy() ); - this.host.removePart( this.side, false ); - Platform.spawnDrops( this.tile.getWorldObj(), this.tile.xCoord, this.tile.yCoord, this.tile.zCoord, items ); - this.is.stackSize = 0; - } - } - private void updateInternalState() { boolean intention = this.getIntention(); - if ( intention == ( this.connection == null ) ) + if( intention == ( this.connection == null ) ) { - if ( this.proxy.getNode() != null && this.outerProxy.getNode() != null ) + if( this.proxy.getNode() != null && this.outerProxy.getNode() != null ) { - if ( intention ) + if( intention ) { try { this.connection = AEApi.instance().createGridConnection( this.proxy.getNode(), this.outerProxy.getNode() ); } - catch ( FailedConnection e ) + catch( FailedConnection e ) { // :( } diff --git a/src/main/java/appeng/parts/networking/PartCable.java b/src/main/java/appeng/parts/networking/PartCable.java index 821f03c89..5a1827fec 100644 --- a/src/main/java/appeng/parts/networking/PartCable.java +++ b/src/main/java/appeng/parts/networking/PartCable.java @@ -79,13 +79,7 @@ public class PartCable extends AEBasePart implements IPartCable super( is ); this.proxy.setFlags( GridFlags.PREFERRED ); this.proxy.setIdlePowerUsage( 0.0 ); - this.proxy.myColor = AEColor.values()[( ( ItemMultiPart ) is.getItem() ).variantOf( is.getItemDamage() )]; - } - - @Override - public boolean isConnected( ForgeDirection side ) - { - return this.connections.contains( side ); + this.proxy.myColor = AEColor.values()[( (ItemMultiPart) is.getItem() ).variantOf( is.getItemDamage() )]; } @Override @@ -94,9 +88,193 @@ public class PartCable extends AEBasePart implements IPartCable return BusSupport.CABLE; } + @Override + public AEColor getCableColor() + { + return this.proxy.myColor; + } + + @Override + public AECableType getCableConnectionType() + { + return AECableType.GLASS; + } + + @Override + public boolean changeColor( AEColor newColor, EntityPlayer who ) + { + if( this.getCableColor() != newColor ) + { + ItemStack newPart = null; + + final IParts parts = AEApi.instance().definitions().parts(); + + if( this.getCableConnectionType() == AECableType.GLASS ) + { + newPart = parts.cableGlass().stack( newColor, 1 ); + } + else if( this.getCableConnectionType() == AECableType.COVERED ) + { + newPart = parts.cableCovered().stack( newColor, 1 ); + } + else if( this.getCableConnectionType() == AECableType.SMART ) + { + newPart = parts.cableSmart().stack( newColor, 1 ); + } + else if( this.getCableConnectionType() == AECableType.DENSE ) + { + newPart = parts.cableDense().stack( newColor, 1 ); + } + + boolean hasPermission = true; + + try + { + hasPermission = this.proxy.getSecurity().hasPermission( who, SecurityPermissions.BUILD ); + } + catch( GridAccessException e ) + { + // :P + } + + if( newPart != null && hasPermission ) + { + if( Platform.isClient() ) + { + return true; + } + + this.getHost().removePart( ForgeDirection.UNKNOWN, true ); + this.getHost().addPart( newPart, ForgeDirection.UNKNOWN, who ); + return true; + } + } + return false; + } + + @Override + public void setValidSides( EnumSet sides ) + { + this.proxy.setValidSides( sides ); + } + + @Override + public boolean isConnected( ForgeDirection side ) + { + return this.connections.contains( side ); + } + + public void markForUpdate() + { + this.getHost().markForUpdate(); + } + + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); + + if( Platform.isServer() ) + { + IGridNode n = this.getGridNode(); + if( n != null ) + { + this.connections = n.getConnectedSides(); + } + else + { + this.connections.clear(); + } + } + + IPartHost ph = this.getHost(); + if( ph != null ) + { + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) + { + IPart p = ph.getPart( dir ); + if( p instanceof IGridHost ) + { + double dist = p.cableConnectionRenderTo(); + + if( dist > 8 ) + { + continue; + } + + switch( dir ) + { + case DOWN: + bch.addBox( 6.0, dist, 6.0, 10.0, 6.0, 10.0 ); + break; + case EAST: + bch.addBox( 10.0, 6.0, 6.0, 16.0 - dist, 10.0, 10.0 ); + break; + case NORTH: + bch.addBox( 6.0, 6.0, dist, 10.0, 10.0, 6.0 ); + break; + case SOUTH: + bch.addBox( 6.0, 6.0, 10.0, 10.0, 10.0, 16.0 - dist ); + break; + case UP: + bch.addBox( 6.0, 10.0, 6.0, 10.0, 16.0 - dist, 10.0 ); + break; + case WEST: + bch.addBox( dist, 6.0, 6.0, 6.0, 10.0, 10.0 ); + break; + default: + } + } + } + } + + for( ForgeDirection of : this.connections ) + { + switch( of ) + { + case DOWN: + bch.addBox( 6.0, 0.0, 6.0, 10.0, 6.0, 10.0 ); + break; + case EAST: + bch.addBox( 10.0, 6.0, 6.0, 16.0, 10.0, 10.0 ); + break; + case NORTH: + bch.addBox( 6.0, 6.0, 0.0, 10.0, 10.0, 6.0 ); + break; + case SOUTH: + bch.addBox( 6.0, 6.0, 10.0, 10.0, 10.0, 16.0 ); + break; + case UP: + bch.addBox( 6.0, 10.0, 6.0, 10.0, 16.0, 10.0 ); + break; + case WEST: + bch.addBox( 0.0, 6.0, 6.0, 6.0, 10.0, 10.0 ); + break; + default: + } + } + } + + @Override + @SideOnly( Side.CLIENT ) + public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) + { + GL11.glTranslated( -0.0, -0.0, 0.3 ); + + rh.setTexture( this.getTexture( this.getCableColor() ) ); + rh.setBounds( 6.0f, 6.0f, 2.0f, 10.0f, 10.0f, 14.0f ); + rh.renderInventoryBox( renderer ); + rh.setTexture( null ); + } + + public IIcon getTexture( AEColor c ) + { + return this.getGlassTexture( c ); + } + public IIcon getGlassTexture( AEColor c ) { - switch ( c ) + switch( c ) { case Black: return CableBusTextures.MECable_Black.getIcon(); @@ -139,14 +317,294 @@ public class PartCable extends AEBasePart implements IPartCable return glassCable.item( AEColor.Transparent ).getIconIndex( glassCableStack ); } - public IIcon getTexture( AEColor c ) + @Override + public AENetworkProxy getProxy() { - return this.getGlassTexture( c ); + return this.proxy; + } + + @Override + @SideOnly( Side.CLIENT ) + public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) + { + this.renderCache = rh.useSimplifiedRendering( x, y, z, this, this.renderCache ); + boolean useCovered = false; + boolean requireDetailed = false; + + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) + { + IPart p = this.getHost().getPart( dir ); + if( p instanceof IGridHost ) + { + IGridHost igh = (IGridHost) p; + AECableType type = igh.getCableConnectionType( dir.getOpposite() ); + if( type == AECableType.COVERED || type == AECableType.SMART ) + { + useCovered = true; + break; + } + } + else if( this.connections.contains( dir ) ) + { + TileEntity te = this.tile.getWorldObj().getTileEntity( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ ); + IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; + if( partHost == null && gh != null && gh.getCableConnectionType( dir ) != AECableType.GLASS ) + { + requireDetailed = true; + } + } + } + + if( useCovered ) + { + rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); + } + else + { + rh.setTexture( this.getTexture( this.getCableColor() ) ); + } + + IPartHost ph = this.getHost(); + for( ForgeDirection of : EnumSet.complementOf( this.connections ) ) + { + IPart bp = ph.getPart( of ); + if( bp instanceof IGridHost ) + { + int len = bp.cableConnectionRenderTo(); + if( len < 8 ) + { + switch( of ) + { + case DOWN: + rh.setBounds( 6, len, 6, 10, 6, 10 ); + break; + case EAST: + rh.setBounds( 10, 6, 6, 16 - len, 10, 10 ); + break; + case NORTH: + rh.setBounds( 6, 6, len, 10, 10, 6 ); + break; + case SOUTH: + rh.setBounds( 6, 6, 10, 10, 10, 16 - len ); + break; + case UP: + rh.setBounds( 6, 10, 6, 10, 16 - len, 10 ); + break; + case WEST: + rh.setBounds( len, 6, 6, 6, 10, 10 ); + break; + default: + continue; + } + rh.renderBlock( x, y, z, renderer ); + } + } + } + + if( this.connections.size() != 2 || !this.nonLinear( this.connections ) || useCovered || requireDetailed ) + { + if( useCovered ) + { + rh.setBounds( 5, 5, 5, 11, 11, 11 ); + rh.renderBlock( x, y, z, renderer ); + } + else + { + rh.setBounds( 6, 6, 6, 10, 10, 10 ); + rh.renderBlock( x, y, z, renderer ); + } + + for( ForgeDirection of : this.connections ) + { + this.renderGlassConnection( x, y, z, rh, renderer, of ); + } + } + else + { + IIcon def = this.getTexture( this.getCableColor() ); + rh.setTexture( def ); + + for( ForgeDirection of : this.connections ) + { + rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of, of.getOpposite() ) ) ); + switch( of ) + { + case DOWN: + case UP: + renderer.setRenderBounds( 6 / 16.0, 0, 6 / 16.0, 10 / 16.0, 16 / 16.0, 10 / 16.0 ); + break; + case EAST: + case WEST: + renderer.uvRotateEast = renderer.uvRotateWest = 1; + renderer.uvRotateBottom = renderer.uvRotateTop = 1; + renderer.setRenderBounds( 0, 6 / 16.0, 6 / 16.0, 16 / 16.0, 10 / 16.0, 10 / 16.0 ); + break; + case NORTH: + case SOUTH: + renderer.uvRotateNorth = renderer.uvRotateSouth = 1; + renderer.setRenderBounds( 6 / 16.0, 6 / 16.0, 0, 10 / 16.0, 10 / 16.0, 16 / 16.0 ); + break; + default: + } + } + + rh.renderBlockCurrentBounds( x, y, z, renderer ); + } + + rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); + rh.setTexture( null ); + } + + @Override + public void writeToNBT( NBTTagCompound data ) + { + super.writeToNBT( data ); + + if( Platform.isServer() ) + { + IGridNode node = this.getGridNode(); + int howMany = 0; + + if( node != null ) + { + for( IGridConnection gc : node.getConnections() ) + { + howMany = Math.max( gc.getUsedChannels(), howMany ); + } + + data.setByte( "usedChannels", (byte) howMany ); + } + } + } + + @Override + public void writeToStream( ByteBuf data ) throws IOException + { + int cs = 0; + int sideOut = 0; + + IGridNode n = this.getGridNode(); + if( n != null ) + { + for( ForgeDirection thisSide : ForgeDirection.VALID_DIRECTIONS ) + { + IPart part = this.getHost().getPart( thisSide ); + if( part != null ) + { + if( part.getGridNode() != null ) + { + IReadOnlyCollection set = part.getGridNode().getConnections(); + for( IGridConnection gc : set ) + { + if( this.proxy.getNode().hasFlag( GridFlags.DENSE_CAPACITY ) && gc.getOtherSide( this.proxy.getNode() ).hasFlag( GridFlags.DENSE_CAPACITY ) ) + { + sideOut |= ( gc.getUsedChannels() / 4 ) << ( 4 * thisSide.ordinal() ); + } + else + { + sideOut |= ( gc.getUsedChannels() ) << ( 4 * thisSide.ordinal() ); + } + } + } + } + } + + for( IGridConnection gc : n.getConnections() ) + { + ForgeDirection side = gc.getDirection( n ); + if( side != ForgeDirection.UNKNOWN ) + { + boolean isTier2a = this.proxy.getNode().hasFlag( GridFlags.DENSE_CAPACITY ); + boolean isTier2b = gc.getOtherSide( this.proxy.getNode() ).hasFlag( GridFlags.DENSE_CAPACITY ); + + if( isTier2a && isTier2b ) + { + sideOut |= ( gc.getUsedChannels() / 4 ) << ( 4 * side.ordinal() ); + } + else + { + sideOut |= gc.getUsedChannels() << ( 4 * side.ordinal() ); + } + cs |= ( 1 << side.ordinal() ); + } + } + } + + try + { + if( this.proxy.getEnergy().isNetworkPowered() ) + { + cs |= ( 1 << ForgeDirection.UNKNOWN.ordinal() ); + } + } + catch( GridAccessException e ) + { + // aww... + } + + data.writeByte( (byte) cs ); + data.writeInt( sideOut ); + } + + @Override + public boolean readFromStream( ByteBuf data ) throws IOException + { + int cs = data.readByte(); + int sideOut = data.readInt(); + + EnumSet myC = this.connections.clone(); + boolean wasPowered = this.powered; + this.powered = false; + boolean channelsChanged = false; + + for( ForgeDirection d : ForgeDirection.values() ) + { + if( d != ForgeDirection.UNKNOWN ) + { + int ch = ( sideOut >> ( d.ordinal() * 4 ) ) & 0xF; + if( ch != this.channelsOnSide[d.ordinal()] ) + { + channelsChanged = true; + this.channelsOnSide[d.ordinal()] = ch; + } + } + + if( d == ForgeDirection.UNKNOWN ) + { + int id = 1 << d.ordinal(); + if( id == ( cs & id ) ) + { + this.powered = true; + } + } + else + { + int id = 1 << d.ordinal(); + if( id == ( cs & id ) ) + { + this.connections.add( d ); + } + else + { + this.connections.remove( d ); + } + } + } + + return !myC.equals( this.connections ) || wasPowered != this.powered || channelsChanged; + } + + @Override + @SideOnly( Side.CLIENT ) + public IIcon getBreakingTexture() + { + return this.getTexture( this.getCableColor() ); } public IIcon getCoveredTexture( AEColor c ) { - switch ( c ) + switch( c ) { case Black: return CableBusTextures.MECovered_Black.getIcon(); @@ -189,9 +647,296 @@ public class PartCable extends AEBasePart implements IPartCable return coveredCable.item( AEColor.Transparent ).getIconIndex( coveredCableStack ); } + protected boolean nonLinear( EnumSet sides ) + { + return ( sides.contains( ForgeDirection.EAST ) && sides.contains( ForgeDirection.WEST ) ) || ( sides.contains( ForgeDirection.NORTH ) && sides.contains( ForgeDirection.SOUTH ) ) || ( sides.contains( ForgeDirection.UP ) && sides.contains( ForgeDirection.DOWN ) ); + } + + @SideOnly( Side.CLIENT ) + public void renderGlassConnection( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer, ForgeDirection of ) + { + TileEntity te = this.tile.getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); + IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; + + rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); + + if( gh != null && partHost != null && gh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) + { + rh.setTexture( this.getTexture( partHost.getColor() ) ); + } + else if( partHost == null && gh != null && gh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) + { + rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); + switch( of ) + { + case DOWN: + rh.setBounds( 5, 0, 5, 11, 4, 11 ); + break; + case EAST: + rh.setBounds( 12, 5, 5, 16, 11, 11 ); + break; + case NORTH: + rh.setBounds( 5, 5, 0, 11, 11, 4 ); + break; + case SOUTH: + rh.setBounds( 5, 5, 12, 11, 11, 16 ); + break; + case UP: + rh.setBounds( 5, 12, 5, 11, 16, 11 ); + break; + case WEST: + rh.setBounds( 0, 5, 5, 4, 11, 11 ); + break; + default: + return; + } + + rh.renderBlock( x, y, z, renderer ); + rh.setTexture( this.getTexture( this.getCableColor() ) ); + } + else + { + rh.setTexture( this.getTexture( this.getCableColor() ) ); + } + + switch( of ) + { + case DOWN: + rh.setBounds( 6, 0, 6, 10, 6, 10 ); + break; + case EAST: + rh.setBounds( 10, 6, 6, 16, 10, 10 ); + break; + case NORTH: + rh.setBounds( 6, 6, 0, 10, 10, 6 ); + break; + case SOUTH: + rh.setBounds( 6, 6, 10, 10, 10, 16 ); + break; + case UP: + rh.setBounds( 6, 10, 6, 10, 16, 10 ); + break; + case WEST: + rh.setBounds( 0, 6, 6, 6, 10, 10 ); + break; + default: + return; + } + + rh.renderBlock( x, y, z, renderer ); + rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); + } + + @SideOnly( Side.CLIENT ) + public void renderCoveredConnection( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer, int channels, ForgeDirection of ) + { + TileEntity te = this.tile.getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); + IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + + rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); + if( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getPart( of.getOpposite() ) == null && partHost.getColor() != AEColor.Transparent ) + { + rh.setTexture( this.getGlassTexture( partHost.getColor() ) ); + } + else if( partHost == null && ghh != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) + { + rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); + switch( of ) + { + case DOWN: + rh.setBounds( 5, 0, 5, 11, 4, 11 ); + break; + case EAST: + rh.setBounds( 12, 5, 5, 16, 11, 11 ); + break; + case NORTH: + rh.setBounds( 5, 5, 0, 11, 11, 4 ); + break; + case SOUTH: + rh.setBounds( 5, 5, 12, 11, 11, 16 ); + break; + case UP: + rh.setBounds( 5, 12, 5, 11, 16, 11 ); + break; + case WEST: + rh.setBounds( 0, 5, 5, 4, 11, 11 ); + break; + default: + return; + } + + rh.renderBlock( x, y, z, renderer ); + + rh.setTexture( this.getTexture( this.getCableColor() ) ); + } + else if( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.COVERED && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) + { + rh.setTexture( this.getCoveredTexture( partHost.getColor() ) ); + } + else + { + rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); + } + + switch( of ) + { + case DOWN: + rh.setBounds( 6, 0, 6, 10, 5, 10 ); + break; + case EAST: + rh.setBounds( 11, 6, 6, 16, 10, 10 ); + break; + case NORTH: + rh.setBounds( 6, 6, 0, 10, 10, 5 ); + break; + case SOUTH: + rh.setBounds( 6, 6, 11, 10, 10, 16 ); + break; + case UP: + rh.setBounds( 6, 11, 6, 10, 16, 10 ); + break; + case WEST: + rh.setBounds( 0, 6, 6, 5, 10, 10 ); + break; + default: + return; + } + + rh.renderBlock( x, y, z, renderer ); + rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); + rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); + } + + @SideOnly( Side.CLIENT ) + public void renderSmartConnection( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer, int channels, ForgeDirection of ) + { + TileEntity te = this.tile.getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); + IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + boolean isGlass = false; + AEColor myColor = this.getCableColor(); + + rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); + + if( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getPart( of.getOpposite() ) == null && partHost.getColor() != AEColor.Transparent ) + { + isGlass = true; + rh.setTexture( this.getGlassTexture( myColor = partHost.getColor() ) ); + } + else if( partHost == null && ghh != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) + { + rh.setTexture( this.getSmartTexture( myColor ) ); + switch( of ) + { + case DOWN: + rh.setBounds( 5, 0, 5, 11, 4, 11 ); + break; + case EAST: + rh.setBounds( 12, 5, 5, 16, 11, 11 ); + break; + case NORTH: + rh.setBounds( 5, 5, 0, 11, 11, 4 ); + break; + case SOUTH: + rh.setBounds( 5, 5, 12, 11, 11, 16 ); + break; + case UP: + rh.setBounds( 5, 12, 5, 11, 16, 11 ); + break; + case WEST: + rh.setBounds( 0, 5, 5, 4, 11, 11 ); + break; + default: + return; + } + rh.renderBlock( x, y, z, renderer ); + + this.setSmartConnectionRotations( of, renderer ); + IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); + IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); + + if( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) + { + AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); + ico.setFlip( false, true ); + } + + Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); + Tessellator.instance.setColorOpaque_I( myColor.blackVariant ); + rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); + this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + + Tessellator.instance.setColorOpaque_I( myColor.whiteVariant ); + rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); + this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + + rh.setTexture( this.getTexture( this.getCableColor() ) ); + } + + else if( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) + { + rh.setTexture( this.getSmartTexture( myColor = partHost.getColor() ) ); + } + else + { + rh.setTexture( this.getSmartTexture( this.getCableColor() ) ); + } + + switch( of ) + { + case DOWN: + rh.setBounds( 6, 0, 6, 10, 5, 10 ); + break; + case EAST: + rh.setBounds( 11, 6, 6, 16, 10, 10 ); + break; + case NORTH: + rh.setBounds( 6, 6, 0, 10, 10, 5 ); + break; + case SOUTH: + rh.setBounds( 6, 6, 11, 10, 10, 16 ); + break; + case UP: + rh.setBounds( 6, 11, 6, 10, 16, 10 ); + break; + case WEST: + rh.setBounds( 0, 6, 6, 5, 10, 10 ); + break; + default: + return; + } + + rh.renderBlock( x, y, z, renderer ); + rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); + + if( !isGlass ) + { + this.setSmartConnectionRotations( of, renderer ); + + IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); + IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); + + Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); + Tessellator.instance.setColorOpaque_I( myColor.blackVariant ); + rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); + this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + + Tessellator.instance.setColorOpaque_I( myColor.whiteVariant ); + rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); + this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + } + } + public IIcon getSmartTexture( AEColor c ) { - switch ( c ) + switch( c ) { case Black: return CableBusTextures.MESmart_Black.getIcon(); @@ -234,607 +979,10 @@ public class PartCable extends AEBasePart implements IPartCable return parts.cableCovered().item( AEColor.Transparent ).getIconIndex( smartCableStack ); } - @Override - public AEColor getCableColor() - { - return this.proxy.myColor; - } - - @Override - public AECableType getCableConnectionType() - { - return AECableType.GLASS; - } - - @Override - public AENetworkProxy getProxy() - { - return this.proxy; - } - - public void markForUpdate() - { - this.getHost().markForUpdate(); - } - - @Override - public void writeToNBT( NBTTagCompound data ) - { - super.writeToNBT( data ); - - if ( Platform.isServer() ) - { - IGridNode node = this.getGridNode(); - int howMany = 0; - - if ( node != null ) - { - for ( IGridConnection gc : node.getConnections() ) - { - howMany = Math.max( gc.getUsedChannels(), howMany ); - } - - data.setByte( "usedChannels", ( byte ) howMany ); - } - } - - } - - @Override - public void writeToStream( ByteBuf data ) throws IOException - { - int cs = 0; - int sideOut = 0; - - IGridNode n = this.getGridNode(); - if ( n != null ) - { - for ( ForgeDirection thisSide : ForgeDirection.VALID_DIRECTIONS ) - { - IPart part = this.getHost().getPart( thisSide ); - if ( part != null ) - { - if ( part.getGridNode() != null ) - { - IReadOnlyCollection set = part.getGridNode().getConnections(); - for ( IGridConnection gc : set ) - { - if ( this.proxy.getNode().hasFlag( GridFlags.DENSE_CAPACITY ) && gc.getOtherSide( this.proxy.getNode() ).hasFlag( GridFlags.DENSE_CAPACITY ) ) - { - sideOut |= ( gc.getUsedChannels() / 4 ) << ( 4 * thisSide.ordinal() ); - } - else - { - sideOut |= ( gc.getUsedChannels() ) << ( 4 * thisSide.ordinal() ); - } - } - } - } - } - - for ( IGridConnection gc : n.getConnections() ) - { - ForgeDirection side = gc.getDirection( n ); - if ( side != ForgeDirection.UNKNOWN ) - { - boolean isTier2a = this.proxy.getNode().hasFlag( GridFlags.DENSE_CAPACITY ); - boolean isTier2b = gc.getOtherSide( this.proxy.getNode() ).hasFlag( GridFlags.DENSE_CAPACITY ); - - if ( isTier2a && isTier2b ) - { - sideOut |= ( gc.getUsedChannels() / 4 ) << ( 4 * side.ordinal() ); - } - else - { - sideOut |= gc.getUsedChannels() << ( 4 * side.ordinal() ); - } - cs |= ( 1 << side.ordinal() ); - } - } - } - - try - { - if ( this.proxy.getEnergy().isNetworkPowered() ) - { - cs |= ( 1 << ForgeDirection.UNKNOWN.ordinal() ); - } - } - catch ( GridAccessException e ) - { - // aww... - } - - data.writeByte( ( byte ) cs ); - data.writeInt( sideOut ); - } - - @Override - public boolean readFromStream( ByteBuf data ) throws IOException - { - int cs = data.readByte(); - int sideOut = data.readInt(); - - EnumSet myC = this.connections.clone(); - boolean wasPowered = this.powered; - this.powered = false; - boolean channelsChanged = false; - - for ( ForgeDirection d : ForgeDirection.values() ) - { - if ( d != ForgeDirection.UNKNOWN ) - { - int ch = ( sideOut >> ( d.ordinal() * 4 ) ) & 0xF; - if ( ch != this.channelsOnSide[d.ordinal()] ) - { - channelsChanged = true; - this.channelsOnSide[d.ordinal()] = ch; - } - } - - if ( d == ForgeDirection.UNKNOWN ) - { - int id = 1 << d.ordinal(); - if ( id == ( cs & id ) ) - { - this.powered = true; - } - } - else - { - int id = 1 << d.ordinal(); - if ( id == ( cs & id ) ) - { - this.connections.add( d ); - } - else - { - this.connections.remove( d ); - } - } - } - - return !myC.equals( this.connections ) || wasPowered != this.powered || channelsChanged; - } - - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); - - if ( Platform.isServer() ) - { - IGridNode n = this.getGridNode(); - if ( n != null ) - { - this.connections = n.getConnectedSides(); - } - else - { - this.connections.clear(); - } - } - - IPartHost ph = this.getHost(); - if ( ph != null ) - { - for ( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - IPart p = ph.getPart( dir ); - if ( p instanceof IGridHost ) - { - double dist = p.cableConnectionRenderTo(); - - if ( dist > 8 ) - { - continue; - } - - switch ( dir ) - { - case DOWN: - bch.addBox( 6.0, dist, 6.0, 10.0, 6.0, 10.0 ); - break; - case EAST: - bch.addBox( 10.0, 6.0, 6.0, 16.0 - dist, 10.0, 10.0 ); - break; - case NORTH: - bch.addBox( 6.0, 6.0, dist, 10.0, 10.0, 6.0 ); - break; - case SOUTH: - bch.addBox( 6.0, 6.0, 10.0, 10.0, 10.0, 16.0 - dist ); - break; - case UP: - bch.addBox( 6.0, 10.0, 6.0, 10.0, 16.0 - dist, 10.0 ); - break; - case WEST: - bch.addBox( dist, 6.0, 6.0, 6.0, 10.0, 10.0 ); - break; - default: - } - } - } - } - - for ( ForgeDirection of : this.connections ) - { - switch ( of ) - { - case DOWN: - bch.addBox( 6.0, 0.0, 6.0, 10.0, 6.0, 10.0 ); - break; - case EAST: - bch.addBox( 10.0, 6.0, 6.0, 16.0, 10.0, 10.0 ); - break; - case NORTH: - bch.addBox( 6.0, 6.0, 0.0, 10.0, 10.0, 6.0 ); - break; - case SOUTH: - bch.addBox( 6.0, 6.0, 10.0, 10.0, 10.0, 16.0 ); - break; - case UP: - bch.addBox( 6.0, 10.0, 6.0, 10.0, 16.0, 10.0 ); - break; - case WEST: - bch.addBox( 0.0, 6.0, 6.0, 6.0, 10.0, 10.0 ); - break; - default: - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); - - rh.setTexture( this.getTexture( this.getCableColor() ) ); - rh.setBounds( 6.0f, 6.0f, 2.0f, 10.0f, 10.0f, 14.0f ); - rh.renderInventoryBox( renderer ); - rh.setTexture( null ); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return this.getTexture( this.getCableColor() ); - } - - @SideOnly( Side.CLIENT ) - public void renderGlassConnection( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer, ForgeDirection of ) - { - TileEntity te = this.tile.getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - IPartHost partHost = te instanceof IPartHost ? ( IPartHost ) te : null; - IGridHost gh = te instanceof IGridHost ? ( IGridHost ) te : null; - - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); - - if ( gh != null && partHost != null && gh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getColor() != AEColor.Transparent - && partHost.getPart( of.getOpposite() ) == null ) - { - rh.setTexture( this.getTexture( partHost.getColor() ) ); - } - else if ( partHost == null && gh != null && gh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - switch ( of ) - { - case DOWN: - rh.setBounds( 5, 0, 5, 11, 4, 11 ); - break; - case EAST: - rh.setBounds( 12, 5, 5, 16, 11, 11 ); - break; - case NORTH: - rh.setBounds( 5, 5, 0, 11, 11, 4 ); - break; - case SOUTH: - rh.setBounds( 5, 5, 12, 11, 11, 16 ); - break; - case UP: - rh.setBounds( 5, 12, 5, 11, 16, 11 ); - break; - case WEST: - rh.setBounds( 0, 5, 5, 4, 11, 11 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - else - { - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - - switch ( of ) - { - case DOWN: - rh.setBounds( 6, 0, 6, 10, 6, 10 ); - break; - case EAST: - rh.setBounds( 10, 6, 6, 16, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, 0, 10, 10, 6 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 10, 10, 10, 16 ); - break; - case UP: - rh.setBounds( 6, 10, 6, 10, 16, 10 ); - break; - case WEST: - rh.setBounds( 0, 6, 6, 6, 10, 10 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - } - - protected CableBusTextures getChannelTex( int i, boolean b ) - { - if ( !this.powered ) - { - i = 0; - } - - if ( b ) - { - switch ( i ) - { - default: - return CableBusTextures.Channels10; - case 5: - return CableBusTextures.Channels11; - case 6: - return CableBusTextures.Channels12; - case 7: - return CableBusTextures.Channels13; - case 8: - return CableBusTextures.Channels14; - } - } - else - { - switch ( i ) - { - case 0: - return CableBusTextures.Channels00; - case 1: - return CableBusTextures.Channels01; - case 2: - return CableBusTextures.Channels02; - case 3: - return CableBusTextures.Channels03; - default: - return CableBusTextures.Channels04; - } - } - } - - @SideOnly( Side.CLIENT ) - public void renderCoveredConnection( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer, int channels, ForgeDirection of ) - { - TileEntity te = this.tile.getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - IPartHost partHost = te instanceof IPartHost ? ( IPartHost ) te : null; - IGridHost ghh = te instanceof IGridHost ? ( IGridHost ) te : null; - - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); - if ( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getPart( of.getOpposite() ) == null - && partHost.getColor() != AEColor.Transparent ) - { - rh.setTexture( this.getGlassTexture( partHost.getColor() ) ); - } - else if ( partHost == null && ghh != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - switch ( of ) - { - case DOWN: - rh.setBounds( 5, 0, 5, 11, 4, 11 ); - break; - case EAST: - rh.setBounds( 12, 5, 5, 16, 11, 11 ); - break; - case NORTH: - rh.setBounds( 5, 5, 0, 11, 11, 4 ); - break; - case SOUTH: - rh.setBounds( 5, 5, 12, 11, 11, 16 ); - break; - case UP: - rh.setBounds( 5, 12, 5, 11, 16, 11 ); - break; - case WEST: - rh.setBounds( 0, 5, 5, 4, 11, 11 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - else if ( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.COVERED && partHost.getColor() != AEColor.Transparent - && partHost.getPart( of.getOpposite() ) == null ) - { - rh.setTexture( this.getCoveredTexture( partHost.getColor() ) ); - } - else - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - } - - switch ( of ) - { - case DOWN: - rh.setBounds( 6, 0, 6, 10, 5, 10 ); - break; - case EAST: - rh.setBounds( 11, 6, 6, 16, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, 0, 10, 10, 5 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 11, 10, 10, 16 ); - break; - case UP: - rh.setBounds( 6, 11, 6, 10, 16, 10 ); - break; - case WEST: - rh.setBounds( 0, 6, 6, 5, 10, 10 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - } - - @SideOnly( Side.CLIENT ) - public void renderSmartConnection( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer, int channels, ForgeDirection of ) - { - TileEntity te = this.tile.getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - IPartHost partHost = te instanceof IPartHost ? ( IPartHost ) te : null; - IGridHost ghh = te instanceof IGridHost ? ( IGridHost ) te : null; - boolean isGlass = false; - AEColor myColor = this.getCableColor(); - - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); - - if ( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getPart( of.getOpposite() ) == null - && partHost.getColor() != AEColor.Transparent ) - { - isGlass = true; - rh.setTexture( this.getGlassTexture( myColor = partHost.getColor() ) ); - } - else if ( partHost == null && ghh != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) - { - rh.setTexture( this.getSmartTexture( myColor ) ); - switch ( of ) - { - case DOWN: - rh.setBounds( 5, 0, 5, 11, 4, 11 ); - break; - case EAST: - rh.setBounds( 12, 5, 5, 16, 11, 11 ); - break; - case NORTH: - rh.setBounds( 5, 5, 0, 11, 11, 4 ); - break; - case SOUTH: - rh.setBounds( 5, 5, 12, 11, 11, 16 ); - break; - case UP: - rh.setBounds( 5, 12, 5, 11, 16, 11 ); - break; - case WEST: - rh.setBounds( 0, 5, 5, 4, 11, 11 ); - break; - default: - return; - } - rh.renderBlock( x, y, z, renderer ); - - this.setSmartConnectionRotations( of, renderer ); - IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - - if ( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) - { - AEBaseBlock blk = ( AEBaseBlock ) rh.getBlock(); - FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); - } - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_I( myColor.blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - this.renderAllFaces( ( AEBaseBlock ) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( myColor.whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); - this.renderAllFaces( ( AEBaseBlock ) rh.getBlock(), x, y, z, rh, renderer ); - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - - else if ( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS && partHost.getColor() != AEColor.Transparent - && partHost.getPart( of.getOpposite() ) == null ) - { - rh.setTexture( this.getSmartTexture( myColor = partHost.getColor() ) ); - } - else - { - rh.setTexture( this.getSmartTexture( this.getCableColor() ) ); - } - - switch ( of ) - { - case DOWN: - rh.setBounds( 6, 0, 6, 10, 5, 10 ); - break; - case EAST: - rh.setBounds( 11, 6, 6, 16, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, 0, 10, 10, 5 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 11, 10, 10, 16 ); - break; - case UP: - rh.setBounds( 6, 11, 6, 10, 16, 10 ); - break; - case WEST: - rh.setBounds( 0, 6, 6, 5, 10, 10 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - - if ( !isGlass ) - { - this.setSmartConnectionRotations( of, renderer ); - - IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_I( myColor.blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - this.renderAllFaces( ( AEBaseBlock ) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( myColor.whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); - this.renderAllFaces( ( AEBaseBlock ) rh.getBlock(), x, y, z, rh, renderer ); - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - } - - } - @SideOnly( Side.CLIENT ) protected void setSmartConnectionRotations( ForgeDirection of, RenderBlocks renderer ) { - switch ( of ) + switch( of ) { case UP: case DOWN: @@ -862,16 +1010,54 @@ public class PartCable extends AEBasePart implements IPartCable break; default: break; + } + } + protected CableBusTextures getChannelTex( int i, boolean b ) + { + if( !this.powered ) + { + i = 0; } + if( b ) + { + switch( i ) + { + default: + return CableBusTextures.Channels10; + case 5: + return CableBusTextures.Channels11; + case 6: + return CableBusTextures.Channels12; + case 7: + return CableBusTextures.Channels13; + case 8: + return CableBusTextures.Channels14; + } + } + else + { + switch( i ) + { + case 0: + return CableBusTextures.Channels00; + case 1: + return CableBusTextures.Channels01; + case 2: + return CableBusTextures.Channels02; + case 3: + return CableBusTextures.Channels03; + default: + return CableBusTextures.Channels04; + } + } } @SideOnly( Side.CLIENT ) protected void renderAllFaces( AEBaseBlock blk, int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) { - rh.setBounds( ( float ) renderer.renderMinX * 16.0f, ( float ) renderer.renderMinY * 16.0f, ( float ) renderer.renderMinZ * 16.0f, - ( float ) renderer.renderMaxX * 16.0f, ( float ) renderer.renderMaxY * 16.0f, ( float ) renderer.renderMaxZ * 16.0f ); + rh.setBounds( (float) renderer.renderMinX * 16.0f, (float) renderer.renderMinY * 16.0f, (float) renderer.renderMinZ * 16.0f, (float) renderer.renderMaxX * 16.0f, (float) renderer.renderMaxY * 16.0f, (float) renderer.renderMaxZ * 16.0f ); rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.WEST ), ForgeDirection.WEST, renderer ); rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.EAST ), ForgeDirection.EAST, renderer ); rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.NORTH ), ForgeDirection.NORTH, renderer ); @@ -879,203 +1065,4 @@ public class PartCable extends AEBasePart implements IPartCable rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.DOWN ), ForgeDirection.DOWN, renderer ); rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.UP ), ForgeDirection.UP, renderer ); } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) - { - this.renderCache = rh.useSimplifiedRendering( x, y, z, this, this.renderCache ); - boolean useCovered = false; - boolean requireDetailed = false; - - for ( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - IPart p = this.getHost().getPart( dir ); - if ( p instanceof IGridHost ) - { - IGridHost igh = ( IGridHost ) p; - AECableType type = igh.getCableConnectionType( dir.getOpposite() ); - if ( type == AECableType.COVERED || type == AECableType.SMART ) - { - useCovered = true; - break; - } - } - else if ( this.connections.contains( dir ) ) - { - TileEntity te = this.tile.getWorldObj().getTileEntity( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ ); - IPartHost partHost = te instanceof IPartHost ? ( IPartHost ) te : null; - IGridHost gh = te instanceof IGridHost ? ( IGridHost ) te : null; - if ( partHost == null && gh != null && gh.getCableConnectionType( dir ) != AECableType.GLASS ) - { - requireDetailed = true; - } - } - } - - if ( useCovered ) - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - } - else - { - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - - IPartHost ph = this.getHost(); - for ( ForgeDirection of : EnumSet.complementOf( this.connections ) ) - { - IPart bp = ph.getPart( of ); - if ( bp instanceof IGridHost ) - { - int len = bp.cableConnectionRenderTo(); - if ( len < 8 ) - { - switch ( of ) - { - case DOWN: - rh.setBounds( 6, len, 6, 10, 6, 10 ); - break; - case EAST: - rh.setBounds( 10, 6, 6, 16 - len, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, len, 10, 10, 6 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 10, 10, 10, 16 - len ); - break; - case UP: - rh.setBounds( 6, 10, 6, 10, 16 - len, 10 ); - break; - case WEST: - rh.setBounds( len, 6, 6, 6, 10, 10 ); - break; - default: - continue; - } - rh.renderBlock( x, y, z, renderer ); - } - } - } - - if ( this.connections.size() != 2 || !this.nonLinear( this.connections ) || useCovered || requireDetailed ) - { - if ( useCovered ) - { - rh.setBounds( 5, 5, 5, 11, 11, 11 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - rh.setBounds( 6, 6, 6, 10, 10, 10 ); - rh.renderBlock( x, y, z, renderer ); - } - - for ( ForgeDirection of : this.connections ) - { - this.renderGlassConnection( x, y, z, rh, renderer, of ); - } - } - else - { - IIcon def = this.getTexture( this.getCableColor() ); - rh.setTexture( def ); - - for ( ForgeDirection of : this.connections ) - { - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of, of.getOpposite() ) ) ); - switch ( of ) - { - case DOWN: - case UP: - renderer.setRenderBounds( 6 / 16.0, 0, 6 / 16.0, 10 / 16.0, 16 / 16.0, 10 / 16.0 ); - break; - case EAST: - case WEST: - renderer.uvRotateEast = renderer.uvRotateWest = 1; - renderer.uvRotateBottom = renderer.uvRotateTop = 1; - renderer.setRenderBounds( 0, 6 / 16.0, 6 / 16.0, 16 / 16.0, 10 / 16.0, 10 / 16.0 ); - break; - case NORTH: - case SOUTH: - renderer.uvRotateNorth = renderer.uvRotateSouth = 1; - renderer.setRenderBounds( 6 / 16.0, 6 / 16.0, 0, 10 / 16.0, 10 / 16.0, 16 / 16.0 ); - break; - default: - } - } - - rh.renderBlockCurrentBounds( x, y, z, renderer ); - } - - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - rh.setTexture( null ); - } - - @Override - public boolean changeColor( AEColor newColor, EntityPlayer who ) - { - if ( this.getCableColor() != newColor ) - { - ItemStack newPart = null; - - final IParts parts = AEApi.instance().definitions().parts(); - - if ( this.getCableConnectionType() == AECableType.GLASS ) - { - newPart = parts.cableGlass().stack( newColor, 1 ); - } - else if ( this.getCableConnectionType() == AECableType.COVERED ) - { - newPart = parts.cableCovered().stack( newColor, 1 ); - } - else if ( this.getCableConnectionType() == AECableType.SMART ) - { - newPart = parts.cableSmart().stack( newColor, 1 ); - } - else if ( this.getCableConnectionType() == AECableType.DENSE ) - { - newPart = parts.cableDense().stack( newColor, 1 ); - } - - boolean hasPermission = true; - - try - { - hasPermission = this.proxy.getSecurity().hasPermission( who, SecurityPermissions.BUILD ); - } - catch ( GridAccessException e ) - { - // :P - } - - if ( newPart != null && hasPermission ) - { - if ( Platform.isClient() ) - { - return true; - } - - this.getHost().removePart( ForgeDirection.UNKNOWN, true ); - this.getHost().addPart( newPart, ForgeDirection.UNKNOWN, who ); - return true; - } - } - return false; - } - - @Override - public void setValidSides( EnumSet sides ) - { - this.proxy.setValidSides( sides ); - } - - protected boolean nonLinear( EnumSet sides ) - { - return ( sides.contains( ForgeDirection.EAST ) && sides.contains( ForgeDirection.WEST ) ) - || ( sides.contains( ForgeDirection.NORTH ) && sides.contains( ForgeDirection.SOUTH ) ) - || ( sides.contains( ForgeDirection.UP ) && sides.contains( ForgeDirection.DOWN ) ); - } - } diff --git a/src/main/java/appeng/parts/networking/PartCableCovered.java b/src/main/java/appeng/parts/networking/PartCableCovered.java index 42dce8683..f33f5afb4 100644 --- a/src/main/java/appeng/parts/networking/PartCableCovered.java +++ b/src/main/java/appeng/parts/networking/PartCableCovered.java @@ -67,12 +67,6 @@ public class PartCableCovered extends PartCable this.getHost().markForUpdate(); } - @Override - public IIcon getTexture( AEColor c ) - { - return this.getCoveredTexture( c ); - } - @Override public AECableType getCableConnectionType() { @@ -84,18 +78,18 @@ public class PartCableCovered extends PartCable { bch.addBox( 5.0, 5.0, 5.0, 11.0, 11.0, 11.0 ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { IGridNode n = this.getGridNode(); - if ( n != null ) + if( n != null ) this.connections = n.getConnectedSides(); else this.connections.clear(); } - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { - switch ( of ) + switch( of ) { case DOWN: bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); @@ -132,7 +126,7 @@ public class PartCableCovered extends PartCable OffsetIcon main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - for ( ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) + for( ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) { rh.renderInventoryFace( main, side, renderer ); } @@ -141,14 +135,14 @@ public class PartCableCovered extends PartCable offV = 0; main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - for ( ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) + for( ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) { rh.renderInventoryFace( main, side, renderer ); } main = new OffsetIcon( this.getTexture( this.getCableColor() ), 0, 0 ); - for ( ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) + for( ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) { rh.renderInventoryFace( main, side, renderer ); } @@ -156,6 +150,12 @@ public class PartCableCovered extends PartCable rh.setTexture( null ); } + @Override + public IIcon getTexture( AEColor c ) + { + return this.getCoveredTexture( c ); + } + @Override @SideOnly( Side.CLIENT ) public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) @@ -167,21 +167,21 @@ public class PartCableCovered extends PartCable boolean hasBuses = false; IPartHost ph = this.getHost(); - for ( ForgeDirection of : EnumSet.complementOf( this.connections ) ) + for( ForgeDirection of : EnumSet.complementOf( this.connections ) ) { IPart bp = ph.getPart( of ); - if ( bp instanceof IGridHost ) + if( bp instanceof IGridHost ) { - if ( of != ForgeDirection.UNKNOWN ) + if( of != ForgeDirection.UNKNOWN ) { sides.add( of ); hasBuses = true; } int len = bp.cableConnectionRenderTo(); - if ( len < 8 ) + if( len < 8 ) { - switch ( of ) + switch( of ) { case DOWN: rh.setBounds( 6, len, 6, 10, 5, 10 ); @@ -209,9 +209,9 @@ public class PartCableCovered extends PartCable } } - if ( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) + if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) { - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { this.renderCoveredConnection( x, y, z, rh, renderer, this.channelsOnSide[of.ordinal()], of ); } @@ -224,9 +224,9 @@ public class PartCableCovered extends PartCable { IIcon def = this.getTexture( this.getCableColor() ); IIcon off = new OffsetIcon( def, 0, -12 ); - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { - switch ( of ) + switch( of ) { case DOWN: case UP: diff --git a/src/main/java/appeng/parts/networking/PartCableSmart.java b/src/main/java/appeng/parts/networking/PartCableSmart.java index 761c89f19..7553df0cc 100644 --- a/src/main/java/appeng/parts/networking/PartCableSmart.java +++ b/src/main/java/appeng/parts/networking/PartCableSmart.java @@ -77,79 +77,23 @@ public class PartCableSmart extends PartCable return AECableType.SMART; } - @Override - public IIcon getTexture( AEColor c ) - { - return this.getSmartTexture( c ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); - - float offU = 0; - float offV = 9; - - OffsetIcon main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - OffsetIcon ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); - OffsetIcon ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); - - for ( ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) - { - rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - offU = 9; - offV = 0; - main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); - ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); - - for ( ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) - { - rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - main = new OffsetIcon( this.getTexture( this.getCableColor() ), 0, 0 ); - ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), 0, 0 ); - ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), 0, 0 ); - - for ( ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) - { - rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - rh.setTexture( null ); - } - @Override public void getBoxes( IPartCollisionHelper bch ) { bch.addBox( 5.0, 5.0, 5.0, 11.0, 11.0, 11.0 ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { IGridNode n = this.getGridNode(); - if ( n != null ) + if( n != null ) this.connections = n.getConnectedSides(); else this.connections.clear(); } - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { - switch ( of ) + switch( of ) { case DOWN: bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); @@ -174,6 +118,62 @@ public class PartCableSmart extends PartCable } } + @Override + @SideOnly( Side.CLIENT ) + public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) + { + GL11.glTranslated( -0.0, -0.0, 0.3 ); + + float offU = 0; + float offV = 9; + + OffsetIcon main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); + OffsetIcon ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); + OffsetIcon ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); + + for( ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) + { + rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); + rh.renderInventoryFace( main, side, renderer ); + rh.renderInventoryFace( ch1, side, renderer ); + rh.renderInventoryFace( ch2, side, renderer ); + } + + offU = 9; + offV = 0; + main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); + ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); + ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); + + for( ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) + { + rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); + rh.renderInventoryFace( main, side, renderer ); + rh.renderInventoryFace( ch1, side, renderer ); + rh.renderInventoryFace( ch2, side, renderer ); + } + + main = new OffsetIcon( this.getTexture( this.getCableColor() ), 0, 0 ); + ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), 0, 0 ); + ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), 0, 0 ); + + for( ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) + { + rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); + rh.renderInventoryFace( main, side, renderer ); + rh.renderInventoryFace( ch1, side, renderer ); + rh.renderInventoryFace( ch2, side, renderer ); + } + + rh.setTexture( null ); + } + + @Override + public IIcon getTexture( AEColor c ) + { + return this.getSmartTexture( c ); + } + @Override @SideOnly( Side.CLIENT ) public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) @@ -185,21 +185,21 @@ public class PartCableSmart extends PartCable boolean hasBuses = false; IPartHost ph = this.getHost(); - for ( ForgeDirection of : EnumSet.complementOf( this.connections ) ) + for( ForgeDirection of : EnumSet.complementOf( this.connections ) ) { IPart bp = ph.getPart( of ); - if ( bp instanceof IGridHost ) + if( bp instanceof IGridHost ) { - if ( of != ForgeDirection.UNKNOWN ) + if( of != ForgeDirection.UNKNOWN ) { sides.add( of ); hasBuses = true; } int len = bp.cableConnectionRenderTo(); - if ( len < 8 ) + if( len < 8 ) { - switch ( of ) + switch( of ) { case DOWN: rh.setBounds( 6, len, 6, 10, 5, 10 ); @@ -228,7 +228,7 @@ public class PartCableSmart extends PartCable IIcon firstIcon = new TaughtIcon( this.getChannelTex( this.channelsOnSide[of.ordinal()], false ).getIcon(), -0.2f ); IIcon secondIcon = new TaughtIcon( this.getChannelTex( this.channelsOnSide[of.ordinal()], true ).getIcon(), -0.2f ); - if ( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) + if( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) { AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); @@ -251,9 +251,9 @@ public class PartCableSmart extends PartCable } } - if ( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) + if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) { - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { this.renderSmartConnection( x, y, z, rh, renderer, this.channelsOnSide[of.ordinal()], of ); } @@ -266,7 +266,7 @@ public class PartCableSmart extends PartCable { ForgeDirection selectedSide = ForgeDirection.UNKNOWN; - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { selectedSide = of; break; @@ -282,7 +282,7 @@ public class PartCableSmart extends PartCable IIcon secondTaughtIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); IIcon secondOffsetIcon = new OffsetIcon( secondTaughtIcon, 0, -12 ); - switch ( selectedSide ) + switch( selectedSide ) { case DOWN: case UP: diff --git a/src/main/java/appeng/parts/networking/PartDenseCable.java b/src/main/java/appeng/parts/networking/PartDenseCable.java index 1d49c51e6..ffd5dcdf2 100644 --- a/src/main/java/appeng/parts/networking/PartDenseCable.java +++ b/src/main/java/appeng/parts/networking/PartDenseCable.java @@ -71,17 +71,6 @@ public class PartDenseCable extends PartCable return BusSupport.DENSE_CABLE; } - @Override - public IIcon getTexture( AEColor c ) - { - if ( c == AEColor.Transparent ) - { - return AEApi.instance().definitions().parts().cableSmart().stack( AEColor.Transparent, 1 ).getIconIndex(); - } - - return this.getSmartTexture( c ); - } - @Override public AECableType getCableConnectionType() { @@ -97,20 +86,20 @@ public class PartDenseCable extends PartCable bch.addBox( min, min, min, max, max, max ); - if ( Platform.isServer() ) + if( Platform.isServer() ) { IGridNode n = this.getGridNode(); - if ( n != null ) + if( n != null ) this.connections = n.getConnectedSides(); else this.connections.clear(); } - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { - if ( this.isDense( of ) ) + if( this.isDense( of ) ) { - switch ( of ) + switch( of ) { case DOWN: bch.addBox( min, 0.0, min, max, min, max ); @@ -135,7 +124,7 @@ public class PartDenseCable extends PartCable } else { - switch ( of ) + switch( of ) { case DOWN: bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); @@ -175,7 +164,7 @@ public class PartDenseCable extends PartCable OffsetIcon ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); OffsetIcon ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); - for ( ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) + for( ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) { rh.renderInventoryFace( main, side, renderer ); rh.renderInventoryFace( ch1, side, renderer ); @@ -188,7 +177,7 @@ public class PartDenseCable extends PartCable ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); - for ( ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) + for( ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) { rh.renderInventoryFace( main, side, renderer ); rh.renderInventoryFace( ch1, side, renderer ); @@ -199,7 +188,7 @@ public class PartDenseCable extends PartCable ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), 0, 0 ); ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), 0, 0 ); - for ( ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) + for( ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) { rh.renderInventoryFace( main, side, renderer ); rh.renderInventoryFace( ch1, side, renderer ); @@ -209,6 +198,17 @@ public class PartDenseCable extends PartCable rh.setTexture( null ); } + @Override + public IIcon getTexture( AEColor c ) + { + if( c == AEColor.Transparent ) + { + return AEApi.instance().definitions().parts().cableSmart().stack( AEColor.Transparent, 1 ).getIconIndex(); + } + + return this.getSmartTexture( c ); + } + @Override @SideOnly( Side.CLIENT ) public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) @@ -219,19 +219,19 @@ public class PartDenseCable extends PartCable EnumSet sides = this.connections.clone(); boolean hasBuses = false; - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { - if ( !this.isDense( of ) ) + if( !this.isDense( of ) ) hasBuses = true; } - if ( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) + if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) { - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { - if ( this.isDense( of ) ) + if( this.isDense( of ) ) this.renderDenseConnection( x, y, z, rh, renderer, this.channelsOnSide[of.ordinal()], of ); - else if ( this.isSmart( of ) ) + else if( this.isSmart( of ) ) this.renderSmartConnection( x, y, z, rh, renderer, this.channelsOnSide[of.ordinal()], of ); else this.renderCoveredConnection( x, y, z, rh, renderer, this.channelsOnSide[of.ordinal()], of ); @@ -245,7 +245,7 @@ public class PartDenseCable extends PartCable { ForgeDirection selectedSide = ForgeDirection.UNKNOWN; - for ( ForgeDirection of : this.connections ) + for( ForgeDirection of : this.connections ) { selectedSide = of; break; @@ -261,7 +261,7 @@ public class PartDenseCable extends PartCable IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); IIcon secondOffset = new OffsetIcon( secondIcon, 0, -12 ); - switch ( selectedSide ) + switch( selectedSide ) { case DOWN: case UP: @@ -387,12 +387,12 @@ public class PartDenseCable extends PartCable */ rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of, of.getOpposite() ) ) ); - if ( ghh != null && partHost != null && ghh.getCableConnectionType( of ) != AECableType.GLASS && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) + if( ghh != null && partHost != null && ghh.getCableConnectionType( of ) != AECableType.GLASS && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) rh.setTexture( this.getTexture( myColor = partHost.getColor() ) ); else rh.setTexture( this.getTexture( this.getCableColor() ) ); - switch ( of ) + switch( of ) { case DOWN: rh.setBounds( 4, 0, 4, 12, 5, 12 ); @@ -419,7 +419,7 @@ public class PartDenseCable extends PartCable rh.renderBlock( x, y, z, renderer ); rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - if ( !isGlass ) + if( !isGlass ) { this.setSmartConnectionRotations( of, renderer ); @@ -442,7 +442,7 @@ public class PartDenseCable extends PartCable private boolean isSmart( ForgeDirection of ) { TileEntity te = this.tile.getWorldObj().getTileEntity( this.tile.xCoord + of.offsetX, this.tile.yCoord + of.offsetY, this.tile.zCoord + of.offsetZ ); - if ( te instanceof IGridHost ) + if( te instanceof IGridHost ) { AECableType t = ( (IGridHost) te ).getCableConnectionType( of.getOpposite() ); return t == AECableType.SMART; @@ -452,7 +452,7 @@ public class PartDenseCable extends PartCable private IIcon getDenseTexture( AEColor c ) { - switch ( c ) + switch( c ) { case Black: return CableBusTextures.MEDense_Black.getIcon(); @@ -495,7 +495,7 @@ public class PartDenseCable extends PartCable private boolean isDense( ForgeDirection of ) { TileEntity te = this.tile.getWorldObj().getTileEntity( this.tile.xCoord + of.offsetX, this.tile.yCoord + of.offsetY, this.tile.zCoord + of.offsetZ ); - if ( te instanceof IGridHost ) + if( te instanceof IGridHost ) { AECableType t = ( (IGridHost) te ).getCableConnectionType( of.getOpposite() ); return t == AECableType.DENSE; diff --git a/src/main/java/appeng/parts/networking/PartQuartzFiber.java b/src/main/java/appeng/parts/networking/PartQuartzFiber.java index 6ae77833b..13ee23afe 100644 --- a/src/main/java/appeng/parts/networking/PartQuartzFiber.java +++ b/src/main/java/appeng/parts/networking/PartQuartzFiber.java @@ -18,6 +18,7 @@ package appeng.parts.networking; + import java.util.EnumSet; import java.util.Set; @@ -47,12 +48,14 @@ import appeng.me.GridAccessException; import appeng.me.helpers.AENetworkProxy; import appeng.parts.AEBasePart; + public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider { final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", this.proxy.getMachineRepresentation(), true ); - public PartQuartzFiber(ItemStack is) { + public PartQuartzFiber( ItemStack is ) + { super( is ); this.proxy.setIdlePowerUsage( 0 ); this.proxy.setFlags( GridFlags.CANNOT_CARRY ); @@ -61,79 +64,20 @@ public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider } @Override - public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) - { - super.onPlacement( player, held, side ); - this.outerProxy.setOwner( player ); - } - - @Override - public void setPartHostInfo(ForgeDirection side, IPartHost host, TileEntity tile) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side ) ); - } - - @Override - public void readFromNBT(NBTTagCompound extra) - { - super.readFromNBT( extra ); - this.outerProxy.readFromNBT( extra ); - } - - @Override - public void writeToNBT(NBTTagCompound extra) - { - super.writeToNBT( extra ); - this.outerProxy.writeToNBT( extra ); - } - - @Override - public void addToWorld() - { - super.addToWorld(); - this.outerProxy.onReady(); - } - - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.outerProxy.invalidate(); - } - - @Override - public IGridNode getExternalFacingNode() - { - return this.outerProxy.getNode(); - } - - @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.GLASS; } @Override - @SideOnly(Side.CLIENT) - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) - { - IIcon myIcon = this.is.getIconIndex(); - rh.setTexture( myIcon ); - rh.setBounds( 6, 6, 10, 10, 10, 16 ); - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( null ); - } - - @Override - public void getBoxes(IPartCollisionHelper bch) + public void getBoxes( IPartCollisionHelper bch ) { bch.addBox( 6, 6, 10, 10, 10, 16 ); } @Override - @SideOnly(Side.CLIENT) - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) + @SideOnly( Side.CLIENT ) + public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) { GL11.glTranslated( -0.2, -0.3, 0.0 ); @@ -144,60 +88,55 @@ public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider } @Override - public double extractAEPower(double amt, Actionable mode, Set seen) + @SideOnly( Side.CLIENT ) + public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) { - double acquiredPower = 0; - - try - { - IEnergyGrid eg = this.proxy.getEnergy(); - acquiredPower += eg.extractAEPower( amt - acquiredPower, mode, seen ); - } - catch (GridAccessException e) - { - // :P - } - - try - { - IEnergyGrid eg = this.outerProxy.getEnergy(); - acquiredPower += eg.extractAEPower( amt - acquiredPower, mode, seen ); - } - catch (GridAccessException e) - { - // :P - } - - return acquiredPower; + IIcon myIcon = this.is.getIconIndex(); + rh.setTexture( myIcon ); + rh.setBounds( 6, 6, 10, 10, 10, 16 ); + rh.renderBlock( x, y, z, renderer ); + rh.setTexture( null ); } @Override - public double injectAEPower(double amt, Actionable mode, Set seen) + public void readFromNBT( NBTTagCompound extra ) { + super.readFromNBT( extra ); + this.outerProxy.readFromNBT( extra ); + } - try - { - IEnergyGrid eg = this.proxy.getEnergy(); - if ( !seen.contains( eg ) ) - return eg.injectAEPower( amt, mode, seen ); - } - catch (GridAccessException e) - { - // :P - } + @Override + public void writeToNBT( NBTTagCompound extra ) + { + super.writeToNBT( extra ); + this.outerProxy.writeToNBT( extra ); + } - try - { - IEnergyGrid eg = this.outerProxy.getEnergy(); - if ( !seen.contains( eg ) ) - return eg.injectAEPower( amt, mode, seen ); - } - catch (GridAccessException e) - { - // :P - } + @Override + public void removeFromWorld() + { + super.removeFromWorld(); + this.outerProxy.invalidate(); + } - return amt; + @Override + public void addToWorld() + { + super.addToWorld(); + this.outerProxy.onReady(); + } + + @Override + public void setPartHostInfo( ForgeDirection side, IPartHost host, TileEntity tile ) + { + super.setPartHostInfo( side, host, tile ); + this.outerProxy.setValidSides( EnumSet.of( side ) ); + } + + @Override + public IGridNode getExternalFacingNode() + { + return this.outerProxy.getNode(); } @Override @@ -207,7 +146,71 @@ public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider } @Override - public double getEnergyDemand(double amt, Set seen) + public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) + { + super.onPlacement( player, held, side ); + this.outerProxy.setOwner( player ); + } + + @Override + public double extractAEPower( double amt, Actionable mode, Set seen ) + { + double acquiredPower = 0; + + try + { + IEnergyGrid eg = this.proxy.getEnergy(); + acquiredPower += eg.extractAEPower( amt - acquiredPower, mode, seen ); + } + catch( GridAccessException e ) + { + // :P + } + + try + { + IEnergyGrid eg = this.outerProxy.getEnergy(); + acquiredPower += eg.extractAEPower( amt - acquiredPower, mode, seen ); + } + catch( GridAccessException e ) + { + // :P + } + + return acquiredPower; + } + + @Override + public double injectAEPower( double amt, Actionable mode, Set seen ) + { + + try + { + IEnergyGrid eg = this.proxy.getEnergy(); + if( !seen.contains( eg ) ) + return eg.injectAEPower( amt, mode, seen ); + } + catch( GridAccessException e ) + { + // :P + } + + try + { + IEnergyGrid eg = this.outerProxy.getEnergy(); + if( !seen.contains( eg ) ) + return eg.injectAEPower( amt, mode, seen ); + } + catch( GridAccessException e ) + { + // :P + } + + return amt; + } + + @Override + public double getEnergyDemand( double amt, Set seen ) { double demand = 0; @@ -216,7 +219,7 @@ public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider IEnergyGrid eg = this.proxy.getEnergy(); demand += eg.getEnergyDemand( amt - demand, seen ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // :P } @@ -226,12 +229,11 @@ public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider IEnergyGrid eg = this.outerProxy.getEnergy(); demand += eg.getEnergyDemand( amt - demand, seen ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // :P } return demand; } - } diff --git a/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java b/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java index 5b07e15d3..3e350feee 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java +++ b/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java @@ -18,6 +18,7 @@ package appeng.parts.p2p; + import java.util.LinkedList; import net.minecraft.init.Blocks; @@ -37,35 +38,32 @@ import appeng.transformer.annotations.Integration.Interface; import appeng.transformer.annotations.Integration.InterfaceList; import appeng.util.Platform; -@InterfaceList(value = { @Interface(iface = "ic2.api.energy.tile.IEnergySink", iname = "IC2"), - @Interface(iface = "ic2.api.energy.tile.IEnergySource", iname = "IC2") }) + +@InterfaceList( value = { @Interface( iface = "ic2.api.energy.tile.IEnergySink", iname = "IC2" ), @Interface( iface = "ic2.api.energy.tile.IEnergySource", iname = "IC2" ) } ) public class PartP2PIC2Power extends PartP2PTunnel implements ic2.api.energy.tile.IEnergySink, ic2.api.energy.tile.IEnergySource { - public PartP2PIC2Power(ItemStack is) { - super( is ); - } - // two packet buffering... double OutputEnergyA; double OutputEnergyB; - // two packet buffering... double OutputVoltageA; double OutputVoltageB; - @Override - public void writeToNBT(NBTTagCompound tag) + public PartP2PIC2Power( ItemStack is ) { - super.writeToNBT( tag ); - tag.setDouble( "OutputPacket", this.OutputEnergyA ); - tag.setDouble( "OutputPacket2", this.OutputEnergyB ); - tag.setDouble( "OutputVoltageA", this.OutputVoltageA ); - tag.setDouble( "OutputVoltageB", this.OutputVoltageB ); + super( is ); } @Override - public void readFromNBT(NBTTagCompound tag) + @SideOnly( Side.CLIENT ) + public IIcon getTypeTexture() + { + return Blocks.diamond_block.getBlockTextureFromSide( 0 ); + } + + @Override + public void readFromNBT( NBTTagCompound tag ) { super.readFromNBT( tag ); this.OutputEnergyA = tag.getDouble( "OutputPacket" ); @@ -75,50 +73,19 @@ public class PartP2PIC2Power extends PartP2PTunnel implements i } @Override - @SideOnly(Side.CLIENT) - public IIcon getTypeTexture() + public void writeToNBT( NBTTagCompound tag ) { - return Blocks.diamond_block.getBlockTextureFromSide( 0 ); + super.writeToNBT( tag ); + tag.setDouble( "OutputPacket", this.OutputEnergyA ); + tag.setDouble( "OutputPacket2", this.OutputEnergyB ); + tag.setDouble( "OutputVoltageA", this.OutputVoltageA ); + tag.setDouble( "OutputVoltageB", this.OutputVoltageB ); } @Override - public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + public void onTunnelConfigChange() { - if ( !this.output ) - return direction == this.side; - return false; - } - - @Override - public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction) - { - if ( this.output ) - return direction == this.side; - return false; - } - - @Override - public double getDemandedEnergy() - { - if ( this.output ) - return 0; - - try - { - for (PartP2PIC2Power t : this.getOutputs()) - { - if ( t.OutputEnergyA <= 0.0001 || t.OutputEnergyB <= 0.0001 ) - { - return 2048; - } - } - } - catch (GridAccessException e) - { - return 0; - } - - return 0; + this.getHost().partChanged(); } @Override @@ -128,58 +95,93 @@ public class PartP2PIC2Power extends PartP2PTunnel implements i } @Override - public void onTunnelConfigChange() + public boolean acceptsEnergyFrom( TileEntity emitter, ForgeDirection direction ) { - this.getHost().partChanged(); - } - - public float getPowerDrainPerTick() - { - return 0.5f; + if( !this.output ) + return direction == this.side; + return false; } @Override - public double injectEnergy(ForgeDirection directionFrom, double amount, double voltage) + public boolean emitsEnergyTo( TileEntity receiver, ForgeDirection direction ) + { + if( this.output ) + return direction == this.side; + return false; + } + + @Override + public double getDemandedEnergy() + { + if( this.output ) + return 0; + + try + { + for( PartP2PIC2Power t : this.getOutputs() ) + { + if( t.OutputEnergyA <= 0.0001 || t.OutputEnergyB <= 0.0001 ) + { + return 2048; + } + } + } + catch( GridAccessException e ) + { + return 0; + } + + return 0; + } + + @Override + public int getSinkTier() + { + return 4; + } + + @Override + public double injectEnergy( ForgeDirection directionFrom, double amount, double voltage ) { TunnelCollection outs; try { outs = this.getOutputs(); } - catch (GridAccessException e) + catch( GridAccessException e ) { return amount; } - if ( outs.isEmpty() ) + if( outs.isEmpty() ) return amount; LinkedList Options = new LinkedList(); - for (PartP2PIC2Power o : outs) + for( PartP2PIC2Power o : outs ) { - if ( o.OutputEnergyA <= 0.01 ) + if( o.OutputEnergyA <= 0.01 ) Options.add( o ); } - if ( Options.isEmpty() ) + if( Options.isEmpty() ) { - for (PartP2PIC2Power o : outs) - if ( o.OutputEnergyB <= 0.01 ) + for( PartP2PIC2Power o : outs ) + if( o.OutputEnergyB <= 0.01 ) Options.add( o ); } - if ( Options.isEmpty() ) + if( Options.isEmpty() ) { - for (PartP2PIC2Power o : outs) + for( PartP2PIC2Power o : outs ) Options.add( o ); } - if ( Options.isEmpty() ) + if( Options.isEmpty() ) return amount; PartP2PIC2Power x = Platform.pickRandom( Options ); - if ( x != null && x.OutputEnergyA <= 0.001 ) + if( x != null && x.OutputEnergyA <= 0.001 ) { this.QueueTunnelDrain( PowerUnits.EU, amount ); x.OutputEnergyA = amount; @@ -187,7 +189,7 @@ public class PartP2PIC2Power extends PartP2PTunnel implements i return 0; } - if ( x != null && x.OutputEnergyB <= 0.001 ) + if( x != null && x.OutputEnergyB <= 0.001 ) { this.QueueTunnelDrain( PowerUnits.EU, amount ); x.OutputEnergyB = amount; @@ -198,25 +200,24 @@ public class PartP2PIC2Power extends PartP2PTunnel implements i return amount; } - @Override - public int getSinkTier() + public float getPowerDrainPerTick() { - return 4; + return 0.5f; } @Override public double getOfferedEnergy() { - if ( this.output ) + if( this.output ) return this.OutputEnergyA; return 0; } @Override - public void drawEnergy(double amount) + public void drawEnergy( double amount ) { this.OutputEnergyA -= amount; - if ( this.OutputEnergyA < 0.001 ) + if( this.OutputEnergyA < 0.001 ) { this.OutputEnergyA = this.OutputEnergyB; this.OutputEnergyB = 0; @@ -229,14 +230,13 @@ public class PartP2PIC2Power extends PartP2PTunnel implements i @Override public int getSourceTier() { - if ( this.output ) + if( this.output ) return this.calculateTierFromVoltage( this.OutputVoltageA ); return 4; } - private int calculateTierFromVoltage(double voltage) + private int calculateTierFromVoltage( double voltage ) { return ic2.api.energy.EnergyNet.instance.getTierFromPower( voltage ); } - } diff --git a/src/main/java/appeng/parts/p2p/PartP2PItems.java b/src/main/java/appeng/parts/p2p/PartP2PItems.java index 47e338a57..8febadf6c 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PItems.java +++ b/src/main/java/appeng/parts/p2p/PartP2PItems.java @@ -18,6 +18,7 @@ package appeng.parts.p2p; + import java.util.LinkedList; import java.util.List; @@ -59,45 +60,89 @@ import appeng.util.inv.WrapperBCPipe; import appeng.util.inv.WrapperChainedInventory; import appeng.util.inv.WrapperMCISidedInventory; -@Interface(iface = "buildcraft.api.transport.IPipeConnection", iname = "BC") + +@Interface( iface = "buildcraft.api.transport.IPipeConnection", iname = "BC" ) public class PartP2PItems extends PartP2PTunnel implements IPipeConnection, ISidedInventory, IGridTickable { - public PartP2PItems(ItemStack is) { - super( is ); - } - + final LinkedList which = new LinkedList(); int oldSize = 0; boolean requested; IInventory cachedInv; - final LinkedList which = new LinkedList(); + public PartP2PItems( ItemStack is ) + { + super( is ); + } + + @Override + public void onNeighborChanged() + { + this.cachedInv = null; + PartP2PItems input = this.getInput(); + if( input != null && this.output ) + input.onTunnelNetworkChange(); + } + + IInventory getDestination() + { + this.requested = true; + + if( this.cachedInv != null ) + return this.cachedInv; + + List outs = new LinkedList(); + TunnelCollection itemTunnels; + + try + { + itemTunnels = this.getOutputs(); + } + catch( GridAccessException e ) + { + return new AppEngNullInventory(); + } + + for( PartP2PItems t : itemTunnels ) + { + IInventory inv = t.getOutputInv(); + if( inv != null ) + { + if( Platform.getRandomInt() % 2 == 0 ) + outs.add( inv ); + else + outs.add( 0, inv ); + } + } + + return this.cachedInv = new WrapperChainedInventory( outs ); + } IInventory getOutputInv() { IInventory output = null; - if ( this.proxy.isActive() ) + if( this.proxy.isActive() ) { TileEntity te = this.tile.getWorldObj().getTileEntity( this.tile.xCoord + this.side.offsetX, this.tile.yCoord + this.side.offsetY, this.tile.zCoord + this.side.offsetZ ); - if ( this.which.contains( this ) ) + if( this.which.contains( this ) ) return null; this.which.add( this ); - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.BC ) ) { IBC buildcraft = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); - if ( buildcraft != null ) + if( buildcraft != null ) { - if ( buildcraft.isPipe( te, this.side.getOpposite() ) ) + if( buildcraft.isPipe( te, this.side.getOpposite() ) ) { try { output = new WrapperBCPipe( te, this.side.getOpposite() ); } - catch (Throwable ignore) + catch( Throwable ignore ) { } } @@ -110,17 +155,17 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo * WrapperTEPipe( te, side.getOpposite() ); } catch (Throwable ignore) { } } } } */ - if ( output == null ) + if( output == null ) { - if ( te instanceof TileEntityChest ) + if( te instanceof TileEntityChest ) { output = Platform.GetChestInv( te ); } - else if ( te instanceof ISidedInventory ) + else if( te instanceof ISidedInventory ) { output = new WrapperMCISidedInventory( (ISidedInventory) te, this.side.getOpposite() ); } - else if ( te instanceof IInventory ) + else if( te instanceof IInventory ) { output = (IInventory) te; } @@ -133,75 +178,32 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo } @Override - public void onNeighborChanged() - { - this.cachedInv = null; - PartP2PItems input = this.getInput(); - if ( input != null && this.output ) - input.onTunnelNetworkChange(); - } - - @Override - public TickingRequest getTickingRequest(IGridNode node) + public TickingRequest getTickingRequest( IGridNode node ) { return new TickingRequest( TickRates.ItemTunnel.min, TickRates.ItemTunnel.max, false, false ); } @Override - public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) + public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) { boolean wasReq = this.requested; - if ( this.requested && this.cachedInv != null ) - ((WrapperChainedInventory) this.cachedInv).cycleOrder(); + if( this.requested && this.cachedInv != null ) + ( (WrapperChainedInventory) this.cachedInv ).cycleOrder(); this.requested = false; return wasReq ? TickRateModulation.FASTER : TickRateModulation.SLOWER; } - IInventory getDestination() - { - this.requested = true; - - if ( this.cachedInv != null ) - return this.cachedInv; - - List outs = new LinkedList(); - TunnelCollection itemTunnels; - - try - { - itemTunnels = this.getOutputs(); - } - catch (GridAccessException e) - { - return new AppEngNullInventory(); - } - - for (PartP2PItems t : itemTunnels) - { - IInventory inv = t.getOutputInv(); - if ( inv != null ) - { - if ( Platform.getRandomInt() % 2 == 0 ) - outs.add( inv ); - else - outs.add( 0, inv ); - } - } - - return this.cachedInv = new WrapperChainedInventory( outs ); - } - @MENetworkEventSubscribe - public void changeStateA(MENetworkBootingStatusChange bs) + public void changeStateA( MENetworkBootingStatusChange bs ) { - if ( !this.output ) + if( !this.output ) { this.cachedInv = null; int olderSize = this.oldSize; this.oldSize = this.getDestination().getSizeInventory(); - if ( olderSize != this.oldSize ) + if( olderSize != this.oldSize ) { this.getHost().notifyNeighbors(); } @@ -209,14 +211,14 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo } @MENetworkEventSubscribe - public void changeStateB(MENetworkChannelsChanged bs) + public void changeStateB( MENetworkChannelsChanged bs ) { - if ( !this.output ) + if( !this.output ) { this.cachedInv = null; int olderSize = this.oldSize; this.oldSize = this.getDestination().getSizeInventory(); - if ( olderSize != this.oldSize ) + if( olderSize != this.oldSize ) { this.getHost().notifyNeighbors(); } @@ -224,29 +226,36 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo } @MENetworkEventSubscribe - public void changeStateC(MENetworkPowerStatusChange bs) + public void changeStateC( MENetworkPowerStatusChange bs ) { - if ( !this.output ) + if( !this.output ) { this.cachedInv = null; int olderSize = this.oldSize; this.oldSize = this.getDestination().getSizeInventory(); - if ( olderSize != this.oldSize ) + if( olderSize != this.oldSize ) { this.getHost().notifyNeighbors(); } } } + @Override + @SideOnly( Side.CLIENT ) + public IIcon getTypeTexture() + { + return Blocks.hopper.getBlockTextureFromSide( 0 ); + } + @Override public void onTunnelNetworkChange() { - if ( !this.output ) + if( !this.output ) { this.cachedInv = null; int olderSize = this.oldSize; this.oldSize = this.getDestination().getSizeInventory(); - if ( olderSize != this.oldSize ) + if( olderSize != this.oldSize ) { this.getHost().notifyNeighbors(); } @@ -254,16 +263,18 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo else { PartP2PItems input = this.getInput(); - if ( input != null ) + if( input != null ) input.getHost().notifyNeighbors(); } } @Override - @SideOnly(Side.CLIENT) - public IIcon getTypeTexture() + public int[] getAccessibleSlotsFromSide( int var1 ) { - return Blocks.hopper.getBlockTextureFromSide( 0 ); + int[] slots = new int[this.getSizeInventory()]; + for( int x = 0; x < this.getSizeInventory(); x++ ) + slots[x] = x; + return slots; } @Override @@ -273,25 +284,25 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo } @Override - public ItemStack getStackInSlot(int i) + public ItemStack getStackInSlot( int i ) { return this.getDestination().getStackInSlot( i ); } @Override - public ItemStack decrStackSize(int i, int j) + public ItemStack decrStackSize( int i, int j ) { return this.getDestination().decrStackSize( i, j ); } @Override - public ItemStack getStackInSlotOnClosing(int i) + public ItemStack getStackInSlotOnClosing( int i ) { return null; } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public void setInventorySlotContents( int i, ItemStack itemstack ) { this.getDestination().setInventorySlotContents( i, itemstack ); } @@ -314,6 +325,18 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo return this.getDestination().getInventoryStackLimit(); } + @Override + public void markDirty() + { + // eh? + } + + @Override + public boolean isUseableByPlayer( EntityPlayer entityplayer ) + { + return false; + } + @Override public void openInventory() { @@ -325,18 +348,21 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo } @Override - public boolean isItemValidForSlot(int i, net.minecraft.item.ItemStack itemstack) + public boolean isItemValidForSlot( int i, net.minecraft.item.ItemStack itemstack ) { return this.getDestination().isItemValidForSlot( i, itemstack ); } @Override - public int[] getAccessibleSlotsFromSide(int var1) + public boolean canInsertItem( int i, ItemStack itemstack, int j ) { - int[] slots = new int[this.getSizeInventory()]; - for (int x = 0; x < this.getSizeInventory(); x++) - slots[x] = x; - return slots; + return this.getDestination().isItemValidForSlot( i, itemstack ); + } + + @Override + public boolean canExtractItem( int i, ItemStack itemstack, int j ) + { + return false; } public float getPowerDrainPerTick() @@ -345,34 +371,9 @@ public class PartP2PItems extends PartP2PTunnel implements IPipeCo } @Override - public boolean canInsertItem(int i, ItemStack itemstack, int j) - { - return this.getDestination().isItemValidForSlot( i, itemstack ); - } - - @Override - public boolean canExtractItem(int i, ItemStack itemstack, int j) - { - return false; - } - - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) - { - return false; - } - - @Override - @Method(iname = "BC") - public ConnectOverride overridePipeConnection(PipeType type, ForgeDirection with) + @Method( iname = "BC" ) + public ConnectOverride overridePipeConnection( PipeType type, ForgeDirection with ) { return this.side == with && type == PipeType.ITEM ? ConnectOverride.CONNECT : ConnectOverride.DEFAULT; } - - @Override - public void markDirty() - { - // eh? - } - } diff --git a/src/main/java/appeng/parts/p2p/PartP2PLight.java b/src/main/java/appeng/parts/p2p/PartP2PLight.java index 83f9e87ec..a35324dd8 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PLight.java +++ b/src/main/java/appeng/parts/p2p/PartP2PLight.java @@ -18,6 +18,7 @@ package appeng.parts.p2p; + import java.io.IOException; import io.netty.buffer.ByteBuf; @@ -41,75 +42,73 @@ import appeng.api.networking.ticking.TickingRequest; import appeng.core.settings.TickRates; import appeng.me.GridAccessException; + public class PartP2PLight extends PartP2PTunnel implements IGridTickable { - public PartP2PLight(ItemStack is) { - super( is ); - } - int lastValue = 0; float opacity = -1; - public void setLightLevel(int out) + public PartP2PLight( ItemStack is ) { - this.lastValue = out; - this.getHost().markForUpdate(); + super( is ); } @Override - public int getLightLevel() - { - if ( this.output && this.isPowered() ) - return this.blockLight( this.lastValue ); - - return 0; - } - - private int blockLight(int emit) - { - if ( this.opacity < 0 ) - { - TileEntity te = this.getTile(); - this.opacity = 255 - te.getWorldObj().getBlockLightOpacity( te.xCoord + this.side.offsetX, te.yCoord + this.side.offsetY, te.zCoord + this.side.offsetZ ); - } - - return (int) (emit * (this.opacity / 255.0f)); - } - - @Override - public void chanRender(MENetworkChannelsChanged c) + public void chanRender( MENetworkChannelsChanged c ) { this.onTunnelNetworkChange(); super.chanRender( c ); } @Override - public void powerRender(MENetworkPowerStatusChange c) + public void powerRender( MENetworkPowerStatusChange c ) { this.onTunnelNetworkChange(); super.powerRender( c ); } @Override - public void onTunnelNetworkChange() + public void writeToStream( ByteBuf data ) throws IOException { - if ( this.output ) - { - PartP2PLight src = this.getInput(); - if ( src != null && src.proxy.isActive() ) - this.setLightLevel( src.lastValue ); - else - this.getHost().markForUpdate(); - } - else - this.doWork(); + super.writeToStream( data ); + data.writeInt( this.output ? this.lastValue : 0 ); } @Override - public void onTunnelConfigChange() + public boolean readFromStream( ByteBuf data ) throws IOException { - this.onTunnelNetworkChange(); + super.readFromStream( data ); + this.lastValue = data.readInt(); + this.output = this.lastValue > 0; + return false; + } + + private boolean doWork() + { + if( this.output ) + return false; + + TileEntity te = this.getTile(); + World w = te.getWorldObj(); + + int newLevel = w.getBlockLightValue( te.xCoord + this.side.offsetX, te.yCoord + this.side.offsetY, te.zCoord + this.side.offsetZ ); + + if( this.lastValue != newLevel && this.proxy.isActive() ) + { + this.lastValue = newLevel; + try + { + for( PartP2PLight out : this.getOutputs() ) + out.setLightLevel( this.lastValue ); + } + catch( GridAccessException e ) + { + // :P + } + return true; + } + return false; } @Override @@ -119,12 +118,54 @@ public class PartP2PLight extends PartP2PTunnel implements IGridTi this.doWork(); - if ( this.output ) + if( this.output ) this.getHost().markForUpdate(); } @Override - public void writeToNBT(NBTTagCompound tag) + public int getLightLevel() + { + if( this.output && this.isPowered() ) + return this.blockLight( this.lastValue ); + + return 0; + } + + public void setLightLevel( int out ) + { + this.lastValue = out; + this.getHost().markForUpdate(); + } + + private int blockLight( int emit ) + { + if( this.opacity < 0 ) + { + TileEntity te = this.getTile(); + this.opacity = 255 - te.getWorldObj().getBlockLightOpacity( te.xCoord + this.side.offsetX, te.yCoord + this.side.offsetY, te.zCoord + this.side.offsetZ ); + } + + return (int) ( emit * ( this.opacity / 255.0f ) ); + } + + @Override + @SideOnly( Side.CLIENT ) + public IIcon getTypeTexture() + { + return Blocks.quartz_block.getBlockTextureFromSide( 0 ); + } + + @Override + public void readFromNBT( NBTTagCompound tag ) + { + super.readFromNBT( tag ); + if( tag.hasKey( "opacity" ) ) + this.opacity = tag.getFloat( "opacity" ); + this.lastValue = tag.getInteger( "lastValue" ); + } + + @Override + public void writeToNBT( NBTTagCompound tag ) { super.writeToNBT( tag ); tag.setFloat( "opacity", this.opacity ); @@ -132,78 +173,40 @@ public class PartP2PLight extends PartP2PTunnel implements IGridTi } @Override - public void readFromNBT(NBTTagCompound tag) + public void onTunnelConfigChange() { - super.readFromNBT( tag ); - if ( tag.hasKey( "opacity" ) ) - this.opacity = tag.getFloat( "opacity" ); - this.lastValue = tag.getInteger( "lastValue" ); + this.onTunnelNetworkChange(); } @Override - public boolean readFromStream(ByteBuf data) throws IOException + public void onTunnelNetworkChange() { - super.readFromStream( data ); - this.lastValue = data.readInt(); - this.output = this.lastValue > 0; - return false; + if( this.output ) + { + PartP2PLight src = this.getInput(); + if( src != null && src.proxy.isActive() ) + this.setLightLevel( src.lastValue ); + else + this.getHost().markForUpdate(); + } + else + this.doWork(); } @Override - public void writeToStream(ByteBuf data) throws IOException - { - super.writeToStream( data ); - data.writeInt( this.output ? this.lastValue : 0 ); - } - - @Override - @SideOnly(Side.CLIENT) - public IIcon getTypeTexture() - { - return Blocks.quartz_block.getBlockTextureFromSide( 0 ); - } - - @Override - public TickingRequest getTickingRequest(IGridNode node) + public TickingRequest getTickingRequest( IGridNode node ) { return new TickingRequest( TickRates.LightTunnel.min, TickRates.LightTunnel.max, false, false ); } - private boolean doWork() + @Override + public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) { - if ( this.output ) - return false; - - TileEntity te = this.getTile(); - World w = te.getWorldObj(); - - int newLevel = w.getBlockLightValue( te.xCoord + this.side.offsetX, te.yCoord + this.side.offsetY, te.zCoord + this.side.offsetZ ); - - if ( this.lastValue != newLevel && this.proxy.isActive() ) - { - this.lastValue = newLevel; - try - { - for (PartP2PLight out : this.getOutputs()) - out.setLightLevel( this.lastValue ); - } - catch (GridAccessException e) - { - // :P - } - return true; - } - return false; + return this.doWork() ? TickRateModulation.FASTER : TickRateModulation.SLOWER; } public float getPowerDrainPerTick() { return 0.5f; } - - @Override - public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) - { - return this.doWork() ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PLiquids.java b/src/main/java/appeng/parts/p2p/PartP2PLiquids.java index 566f9de37..b2d6e4968 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PLiquids.java +++ b/src/main/java/appeng/parts/p2p/PartP2PLiquids.java @@ -18,6 +18,7 @@ package appeng.parts.p2p; + import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -38,131 +39,58 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.me.GridAccessException; + public class PartP2PLiquids extends PartP2PTunnel implements IFluidHandler { + static final ThreadLocal> DEPTH = new ThreadLocal>(); private final static FluidTankInfo[] ACTIVE_TANK = new FluidTankInfo[] { new FluidTankInfo( null, 10000 ) }; private final static FluidTankInfo[] INACTIVE_TANK = new FluidTankInfo[] { new FluidTankInfo( null, 0 ) }; + IFluidHandler cachedTank; + private int tmpUsed; - public PartP2PLiquids(ItemStack is) { + public PartP2PLiquids( ItemStack is ) + { super( is ); } - private FluidTankInfo[] getTank() - { - if ( this.output ) - { - PartP2PLiquids tun = this.getInput(); - if ( tun != null ) - return ACTIVE_TANK; - } - else - { - try - { - if ( !this.getOutputs().isEmpty() ) - return ACTIVE_TANK; - } - catch (GridAccessException e) - { - // :( - } - } - return INACTIVE_TANK; - } - - IFluidHandler cachedTank; - public float getPowerDrainPerTick() { return 2.0f; } - private int tmpUsed; - @Override - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public IIcon getTypeTexture() { return Blocks.lapis_block.getBlockTextureFromSide( 0 ); } - List getOutputs(Fluid input) - { - List outs = new LinkedList(); - - try - { - for (PartP2PLiquids l : this.getOutputs()) - { - IFluidHandler handler = l.getTarget(); - if ( handler != null ) - { - if ( handler.canFill( l.side.getOpposite(), input ) ) - outs.add( l ); - } - } - } - catch (GridAccessException e) - { - // :P - } - - return outs; - } - - @Override - public void onNeighborChanged() - { - this.cachedTank = null; - if ( this.output ) - { - PartP2PLiquids in = this.getInput(); - if ( in != null ) - in.onTunnelNetworkChange(); - } - } - @Override public void onTunnelNetworkChange() { this.cachedTank = null; } - IFluidHandler getTarget() + @Override + public void onNeighborChanged() { - if ( !this.proxy.isActive() ) - return null; - - if ( this.cachedTank != null ) - return this.cachedTank; - - TileEntity te = this.tile.getWorldObj().getTileEntity( this.tile.xCoord + this.side.offsetX, this.tile.yCoord + this.side.offsetY, this.tile.zCoord + this.side.offsetZ ); - if ( te instanceof IFluidHandler ) - return this.cachedTank = (IFluidHandler) te; - - return null; - } - - static final ThreadLocal> DEPTH = new ThreadLocal>(); - - private Stack getDepth() - { - Stack s = DEPTH.get(); - - if ( s == null ) - DEPTH.set( s = new Stack() ); - - return s; + this.cachedTank = null; + if( this.output ) + { + PartP2PLiquids in = this.getInput(); + if( in != null ) + in.onTunnelNetworkChange(); + } } @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) + public int fill( ForgeDirection from, FluidStack resource, boolean doFill ) { Stack stack = this.getDepth(); - for (PartP2PLiquids t : stack) - if ( t == this ) + for( PartP2PLiquids t : stack ) + if( t == this ) return 0; stack.push( this ); @@ -171,32 +99,32 @@ public class PartP2PLiquids extends PartP2PTunnel implements IFl int requestTotal = 0; Iterator i = list.iterator(); - while (i.hasNext()) + while( i.hasNext() ) { PartP2PLiquids l = i.next(); IFluidHandler tank = l.getTarget(); - if ( tank != null ) + if( tank != null ) l.tmpUsed = tank.fill( l.side.getOpposite(), resource.copy(), false ); else l.tmpUsed = 0; - if ( l.tmpUsed <= 0 ) + if( l.tmpUsed <= 0 ) i.remove(); else requestTotal += l.tmpUsed; } - if ( requestTotal <= 0 ) + if( requestTotal <= 0 ) { - if ( stack.pop() != this ) + if( stack.pop() != this ) throw new RuntimeException( "Invalid Recursion detected." ); return 0; } - if ( !doFill ) + if( !doFill ) { - if ( stack.pop() != this ) + if( stack.pop() != this ) throw new RuntimeException( "Invalid Recursion detected." ); return Math.min( resource.amount, requestTotal ); @@ -206,17 +134,17 @@ public class PartP2PLiquids extends PartP2PTunnel implements IFl int used = 0; i = list.iterator(); - while (i.hasNext()) + while( i.hasNext() ) { PartP2PLiquids l = i.next(); FluidStack insert = resource.copy(); - insert.amount = (int) Math.ceil( insert.amount * ((double) l.tmpUsed / (double) requestTotal) ); - if ( insert.amount > available ) + insert.amount = (int) Math.ceil( insert.amount * ( (double) l.tmpUsed / (double) requestTotal ) ); + if( insert.amount > available ) insert.amount = available; IFluidHandler tank = l.getTarget(); - if ( tank != null ) + if( tank != null ) l.tmpUsed = tank.fill( l.side.getOpposite(), insert.copy(), true ); else l.tmpUsed = 0; @@ -225,42 +153,113 @@ public class PartP2PLiquids extends PartP2PTunnel implements IFl used += insert.amount; } - if ( stack.pop() != this ) + if( stack.pop() != this ) throw new RuntimeException( "Invalid Recursion detected." ); return used; } + private Stack getDepth() + { + Stack s = DEPTH.get(); + + if( s == null ) + DEPTH.set( s = new Stack() ); + + return s; + } + + List getOutputs( Fluid input ) + { + List outs = new LinkedList(); + + try + { + for( PartP2PLiquids l : this.getOutputs() ) + { + IFluidHandler handler = l.getTarget(); + if( handler != null ) + { + if( handler.canFill( l.side.getOpposite(), input ) ) + outs.add( l ); + } + } + } + catch( GridAccessException e ) + { + // :P + } + + return outs; + } + + IFluidHandler getTarget() + { + if( !this.proxy.isActive() ) + return null; + + if( this.cachedTank != null ) + return this.cachedTank; + + TileEntity te = this.tile.getWorldObj().getTileEntity( this.tile.xCoord + this.side.offsetX, this.tile.yCoord + this.side.offsetY, this.tile.zCoord + this.side.offsetZ ); + if( te instanceof IFluidHandler ) + return this.cachedTank = (IFluidHandler) te; + + return null; + } + @Override - public boolean canFill(ForgeDirection from, Fluid fluid) + public FluidStack drain( ForgeDirection from, FluidStack resource, boolean doDrain ) + { + return null; + } + + @Override + public FluidStack drain( ForgeDirection from, int maxDrain, boolean doDrain ) + { + return null; + } + + @Override + public boolean canFill( ForgeDirection from, Fluid fluid ) { return !this.output && from == this.side && !this.getOutputs( fluid ).isEmpty(); } @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) - { - return null; - } - - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) - { - return null; - } - - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) + public boolean canDrain( ForgeDirection from, Fluid fluid ) { return false; } @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) + public FluidTankInfo[] getTankInfo( ForgeDirection from ) { - if ( from == this.side ) + if( from == this.side ) return this.getTank(); return new FluidTankInfo[0]; } + private FluidTankInfo[] getTank() + { + if( this.output ) + { + PartP2PLiquids tun = this.getInput(); + if( tun != null ) + return ACTIVE_TANK; + } + else + { + try + { + if( !this.getOutputs().isEmpty() ) + return ACTIVE_TANK; + } + catch( GridAccessException e ) + { + // :( + } + } + return INACTIVE_TANK; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PRFPower.java b/src/main/java/appeng/parts/p2p/PartP2PRFPower.java index 83cdf02c6..8d19a07cf 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PRFPower.java +++ b/src/main/java/appeng/parts/p2p/PartP2PRFPower.java @@ -56,12 +56,6 @@ public class PartP2PRFPower extends PartP2PTunnel implements IEn super( is ); } - @Override - public void onTunnelNetworkChange() - { - this.getHost().notifyNeighbors(); - } - @Override @SideOnly( Side.CLIENT ) public IIcon getTypeTexture() @@ -69,6 +63,12 @@ public class PartP2PRFPower extends PartP2PTunnel implements IEn return Blocks.iron_block.getBlockTextureFromSide( 0 ); } + @Override + public void onTunnelNetworkChange() + { + this.getHost().notifyNeighbors(); + } + @Override public void onNeighborChanged() { @@ -80,15 +80,15 @@ public class PartP2PRFPower extends PartP2PTunnel implements IEn @Override public int receiveEnergy( ForgeDirection from, int maxReceive, boolean simulate ) { - if ( this.output ) + if( this.output ) return 0; - if ( this.isActive() ) + if( this.isActive() ) { Stack stack = this.getDepth(); - for ( PartP2PRFPower t : stack ) - if ( t == this ) + for( PartP2PRFPower t : stack ) + if( t == this ) return 0; stack.push( this ); @@ -97,39 +97,39 @@ public class PartP2PRFPower extends PartP2PTunnel implements IEn try { - for ( PartP2PRFPower t : this.getOutputs() ) + for( PartP2PRFPower t : this.getOutputs() ) { - if ( Platform.getRandomInt() % 2 > 0 ) + if( Platform.getRandomInt() % 2 > 0 ) { int receiver = t.getOutput().receiveEnergy( t.side.getOpposite(), maxReceive, simulate ); maxReceive -= receiver; total += receiver; - if ( maxReceive <= 0 ) + if( maxReceive <= 0 ) break; } } - if ( maxReceive > 0 ) + if( maxReceive > 0 ) { - for ( PartP2PRFPower t : this.getOutputs() ) + for( PartP2PRFPower t : this.getOutputs() ) { int receiver = t.getOutput().receiveEnergy( t.side.getOpposite(), maxReceive, simulate ); maxReceive -= receiver; total += receiver; - if ( maxReceive <= 0 ) + if( maxReceive <= 0 ) break; } } this.QueueTunnelDrain( PowerUnits.RF, total ); } - catch ( GridAccessException ignored ) + catch( GridAccessException ignored ) { } - if ( stack.pop() != this ) + if( stack.pop() != this ) throw new RuntimeException( "Invalid Recursion detected." ); return total; @@ -142,7 +142,7 @@ public class PartP2PRFPower extends PartP2PTunnel implements IEn { Stack s = THREAD_STACK.get(); - if ( s == null ) + if( s == null ) THREAD_STACK.set( s = new Stack() ); return s; @@ -150,17 +150,17 @@ public class PartP2PRFPower extends PartP2PTunnel implements IEn private IEnergyReceiver getOutput() { - if ( this.output ) + if( this.output ) { - if ( !this.cachedTarget ) + if( !this.cachedTarget ) { TileEntity self = this.getTile(); TileEntity te = self.getWorldObj().getTileEntity( self.xCoord + this.side.offsetX, self.yCoord + this.side.offsetY, self.zCoord + this.side.offsetZ ); - this.outputTarget = te instanceof IEnergyReceiver ? ( IEnergyReceiver ) te : null; + this.outputTarget = te instanceof IEnergyReceiver ? (IEnergyReceiver) te : null; this.cachedTarget = true; } - if ( this.outputTarget == null || !this.outputTarget.canConnectEnergy( this.side.getOpposite() ) ) + if( this.outputTarget == null || !this.outputTarget.canConnectEnergy( this.side.getOpposite() ) ) return NULL_HANDLER; return this.outputTarget; @@ -171,32 +171,32 @@ public class PartP2PRFPower extends PartP2PTunnel implements IEn @Override public int getEnergyStored( ForgeDirection from ) { - if ( this.output || !this.isActive() ) + if( this.output || !this.isActive() ) return 0; int total = 0; Stack stack = this.getDepth(); - for ( PartP2PRFPower t : stack ) - if ( t == this ) + for( PartP2PRFPower t : stack ) + if( t == this ) return 0; stack.push( this ); try { - for ( PartP2PRFPower t : this.getOutputs() ) + for( PartP2PRFPower t : this.getOutputs() ) { total += t.getOutput().getEnergyStored( t.side.getOpposite() ); } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { return 0; } - if ( stack.pop() != this ) + if( stack.pop() != this ) throw new RuntimeException( "Invalid Recursion detected." ); return total; @@ -205,32 +205,32 @@ public class PartP2PRFPower extends PartP2PTunnel implements IEn @Override public int getMaxEnergyStored( ForgeDirection from ) { - if ( this.output || !this.isActive() ) + if( this.output || !this.isActive() ) return 0; int total = 0; Stack stack = this.getDepth(); - for ( PartP2PRFPower t : stack ) - if ( t == this ) + for( PartP2PRFPower t : stack ) + if( t == this ) return 0; stack.push( this ); try { - for ( PartP2PRFPower t : this.getOutputs() ) + for( PartP2PRFPower t : this.getOutputs() ) { total += t.getOutput().getMaxEnergyStored( t.side.getOpposite() ); } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { return 0; } - if ( stack.pop() != this ) + if( stack.pop() != this ) throw new RuntimeException( "Invalid Recursion detected." ); return total; diff --git a/src/main/java/appeng/parts/p2p/PartP2PRedstone.java b/src/main/java/appeng/parts/p2p/PartP2PRedstone.java index ed135abac..30d92997c 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PRedstone.java +++ b/src/main/java/appeng/parts/p2p/PartP2PRedstone.java @@ -18,6 +18,7 @@ package appeng.parts.p2p; + import net.minecraft.block.Block; import net.minecraft.block.BlockRedstoneWire; import net.minecraft.init.Blocks; @@ -36,86 +37,50 @@ import appeng.api.networking.events.MENetworkPowerStatusChange; import appeng.me.GridAccessException; import appeng.util.Platform; + public class PartP2PRedstone extends PartP2PTunnel { - public PartP2PRedstone(ItemStack is) { + int power; + boolean recursive = false; + + public PartP2PRedstone( ItemStack is ) + { super( is ); } - int power; - - @Override - public boolean canConnectRedstone() - { - return true; - } - - @Override - public int isProvidingStrongPower() - { - return this.output ? this.power : 0; - } - - @Override - public int isProvidingWeakPower() - { - return this.output ? this.power : 0; - } - - @Override - public void onTunnelNetworkChange() - { - this.setNetworkReady(); - } - @MENetworkEventSubscribe - public void changeStateA(MENetworkBootingStatusChange bs) - { - this.setNetworkReady(); - } - - @MENetworkEventSubscribe - public void changeStateB(MENetworkChannelsChanged bs) - { - this.setNetworkReady(); - } - - @MENetworkEventSubscribe - public void changeStateC(MENetworkPowerStatusChange bs) + public void changeStateA( MENetworkBootingStatusChange bs ) { this.setNetworkReady(); } public void setNetworkReady() { - if ( this.output ) + if( this.output ) { PartP2PRedstone in = this.getInput(); - if ( in != null ) + if( in != null ) this.putInput( in.power ); } } - boolean recursive = false; - - protected void putInput(Object o) + protected void putInput( Object o ) { - if ( this.recursive ) + if( this.recursive ) return; this.recursive = true; - if ( this.output && this.proxy.isActive() ) + if( this.output && this.proxy.isActive() ) { int newPower = (Integer) o; - if ( this.power != newPower ) + if( this.power != newPower ) { this.power = newPower; this.notifyNeighbors(); } } this.recursive = false; - } public void notifyNeighbors() @@ -137,25 +102,43 @@ public class PartP2PRedstone extends PartP2PTunnel Platform.notifyBlocksOfNeighbors( worldObj, xCoord + 1, yCoord, zCoord ); } - @Override - public void writeToNBT(NBTTagCompound tag) + @MENetworkEventSubscribe + public void changeStateB( MENetworkChannelsChanged bs ) { - super.writeToNBT( tag ); - tag.setInteger( "power", this.power ); + this.setNetworkReady(); + } + + @MENetworkEventSubscribe + public void changeStateC( MENetworkPowerStatusChange bs ) + { + this.setNetworkReady(); } @Override - public void readFromNBT(NBTTagCompound tag) + @SideOnly( Side.CLIENT ) + public IIcon getTypeTexture() + { + return Blocks.redstone_block.getBlockTextureFromSide( 0 ); + } + + @Override + public void readFromNBT( NBTTagCompound tag ) { super.readFromNBT( tag ); this.power = tag.getInteger( "power" ); } @Override - @SideOnly(Side.CLIENT) - public IIcon getTypeTexture() + public void writeToNBT( NBTTagCompound tag ) { - return Blocks.redstone_block.getBlockTextureFromSide( 0 ); + super.writeToNBT( tag ); + tag.setInteger( "power", this.power ); + } + + @Override + public void onTunnelNetworkChange() + { + this.setNetworkReady(); } public float getPowerDrainPerTick() @@ -166,17 +149,17 @@ public class PartP2PRedstone extends PartP2PTunnel @Override public void onNeighborChanged() { - if ( !this.output ) + if( !this.output ) { int x = this.tile.xCoord + this.side.offsetX; int y = this.tile.yCoord + this.side.offsetY; int z = this.tile.zCoord + this.side.offsetZ; Block b = this.tile.getWorldObj().getBlock( x, y, z ); - if ( b != null && !this.output ) + if( b != null && !this.output ) { int srcSide = this.side.ordinal(); - if ( b instanceof BlockRedstoneWire ) + if( b instanceof BlockRedstoneWire ) srcSide = 1; this.power = b.isProvidingStrongPower( this.tile.getWorldObj(), x, y, z, srcSide ); this.power = Math.max( this.power, b.isProvidingWeakPower( this.tile.getWorldObj(), x, y, z, srcSide ) ); @@ -187,19 +170,36 @@ public class PartP2PRedstone extends PartP2PTunnel } } - private void sendToOutput(int power) + @Override + public boolean canConnectRedstone() + { + return true; + } + + @Override + public int isProvidingStrongPower() + { + return this.output ? this.power : 0; + } + + @Override + public int isProvidingWeakPower() + { + return this.output ? this.power : 0; + } + + private void sendToOutput( int power ) { try { - for (PartP2PRedstone rs : this.getOutputs()) + for( PartP2PRedstone rs : this.getOutputs() ) { rs.putInput( power ); } } - catch (GridAccessException e) + catch( GridAccessException e ) { // :P } } - } diff --git a/src/main/java/appeng/parts/p2p/PartP2PTunnel.java b/src/main/java/appeng/parts/p2p/PartP2PTunnel.java index 5086efbaa..389cdfd6b 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PTunnel.java +++ b/src/main/java/appeng/parts/p2p/PartP2PTunnel.java @@ -72,7 +72,7 @@ public abstract class PartP2PTunnel extends PartBasicSt public TunnelCollection getCollection( Collection collection, Class c ) { - if ( this.type.matches( c ) ) + if( this.type.matches( c ) ) { this.type.setSource( collection ); return this.type; @@ -83,17 +83,17 @@ public abstract class PartP2PTunnel extends PartBasicSt public T getInput() { - if ( this.freq == 0 ) + if( this.freq == 0 ) return null; PartP2PTunnel tunnel; try { tunnel = this.proxy.getP2P().getInput( this.freq ); - if ( this.getClass().isInstance( tunnel ) ) + if( this.getClass().isInstance( tunnel ) ) return (T) tunnel; } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -102,11 +102,19 @@ public abstract class PartP2PTunnel extends PartBasicSt public TunnelCollection getOutputs() throws GridAccessException { - if ( this.proxy.isActive() ) + if( this.proxy.isActive() ) return (TunnelCollection) this.proxy.getP2P().getOutputs( this.freq, this.getClass() ); return new TunnelCollection( new ArrayList(), this.getClass() ); } + @Override + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 5, 5, 12, 11, 11, 13 ); + bch.addBox( 3, 3, 13, 13, 13, 14 ); + bch.addBox( 2, 2, 14, 14, 14, 16 ); + } + @Override @SideOnly( Side.CLIENT ) public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) @@ -128,7 +136,7 @@ public abstract class PartP2PTunnel extends PartBasicSt protected IIcon getTypeTexture() { final Optional maybeBlock = AEApi.instance().definitions().blocks().quartz().maybeBlock(); - if ( maybeBlock.isPresent() ) + if( maybeBlock.isPresent() ) { return maybeBlock.get().getIcon( 0, 0 ); } @@ -170,11 +178,11 @@ public abstract class PartP2PTunnel extends PartBasicSt @Override public ItemStack getItemStack( PartItemStack type ) { - if ( type == PartItemStack.World || type == PartItemStack.Network || type == PartItemStack.Wrench || type == PartItemStack.Pick ) + if( type == PartItemStack.World || type == PartItemStack.Network || type == PartItemStack.Wrench || type == PartItemStack.Pick ) return super.getItemStack( type ); final Optional maybeMEStack = AEApi.instance().definitions().parts().p2PTunnelME().maybeStack( 1 ); - if ( maybeMEStack.isPresent() ) + if( maybeMEStack.isPresent() ) { return maybeMEStack.get(); } @@ -198,14 +206,6 @@ public abstract class PartP2PTunnel extends PartBasicSt data.setLong( "freq", this.freq ); } - @Override - public void getBoxes( IPartCollisionHelper bch ) - { - bch.addBox( 5, 5, 12, 11, 11, 13 ); - bch.addBox( 3, 3, 13, 13, 13, 14 ); - bch.addBox( 2, 2, 14, 14, 14, 16 ); - } - @Override public int cableConnectionRenderTo() { @@ -227,7 +227,7 @@ public abstract class PartP2PTunnel extends PartBasicSt // AELog.info( "ID:" + id.toString() + " : " + is.getItemDamage() ); TunnelType tt = AEApi.instance().registries().p2pTunnel().getTunnelTypeByItem( is ); - if ( is != null && is.getItem() instanceof IMemoryCard ) + if( is != null && is.getItem() instanceof IMemoryCard ) { IMemoryCard mc = (IMemoryCard) is.getItem(); NBTTagCompound data = mc.getData( is ); @@ -235,18 +235,18 @@ public abstract class PartP2PTunnel extends PartBasicSt ItemStack newType = ItemStack.loadItemStackFromNBT( data ); long freq = data.getLong( "freq" ); - if ( newType != null ) + if( newType != null ) { - if ( newType.getItem() instanceof IPartItem ) + if( newType.getItem() instanceof IPartItem ) { IPart testPart = ( (IPartItem) newType.getItem() ).createPartFromItemStack( newType ); - if ( testPart instanceof PartP2PTunnel ) + if( testPart instanceof PartP2PTunnel ) { this.getHost().removePart( this.side, true ); ForgeDirection dir = this.getHost().addPart( newType, this.side, player ); IPart newBus = this.getHost().getPart( dir ); - if ( newBus instanceof PartP2PTunnel ) + if( newBus instanceof PartP2PTunnel ) { PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; newTunnel.output = true; @@ -256,7 +256,7 @@ public abstract class PartP2PTunnel extends PartBasicSt P2PCache p2p = newTunnel.proxy.getP2P(); p2p.updateFreq( newTunnel, freq ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -271,58 +271,58 @@ public abstract class PartP2PTunnel extends PartBasicSt } mc.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); } - else if ( tt != null ) // attunement + else if( tt != null ) // attunement { ItemStack newType = null; final IParts parts = AEApi.instance().definitions().parts(); - switch ( tt ) + switch( tt ) { case LIGHT: - for ( ItemStack stack : parts.p2PTunnelLight().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.p2PTunnelLight().maybeStack( 1 ).asSet() ) { newType = stack; } break; case RF_POWER: - for ( ItemStack stack : parts.p2PTunnelRF().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.p2PTunnelRF().maybeStack( 1 ).asSet() ) { newType = stack; } break; case FLUID: - for ( ItemStack stack : parts.p2PTunnelLiquids().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.p2PTunnelLiquids().maybeStack( 1 ).asSet() ) { newType = stack; } break; case IC2_POWER: - for ( ItemStack stack : parts.p2PTunnelEU().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.p2PTunnelEU().maybeStack( 1 ).asSet() ) { newType = stack; } break; case ITEM: - for ( ItemStack stack : parts.p2PTunnelItems().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.p2PTunnelItems().maybeStack( 1 ).asSet() ) { newType = stack; } break; case ME: - for ( ItemStack stack : parts.p2PTunnelME().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.p2PTunnelME().maybeStack( 1 ).asSet() ) { newType = stack; } break; case REDSTONE: - for ( ItemStack stack : parts.p2PTunnelRedstone().maybeStack( 1 ).asSet() ) + for( ItemStack stack : parts.p2PTunnelRedstone().maybeStack( 1 ).asSet() ) { newType = stack; } @@ -332,7 +332,7 @@ public abstract class PartP2PTunnel extends PartBasicSt break; } - if ( newType != null && !Platform.isSameItem( newType, this.is ) ) + if( newType != null && !Platform.isSameItem( newType, this.is ) ) { boolean oldOutput = this.output; long myFreq = this.freq; @@ -341,7 +341,7 @@ public abstract class PartP2PTunnel extends PartBasicSt ForgeDirection dir = this.getHost().addPart( newType, this.side, player ); IPart newBus = this.getHost().getPart( dir ); - if ( newBus instanceof PartP2PTunnel ) + if( newBus instanceof PartP2PTunnel ) { PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; newTunnel.output = oldOutput; @@ -352,7 +352,7 @@ public abstract class PartP2PTunnel extends PartBasicSt P2PCache p2p = newTunnel.proxy.getP2P(); p2p.updateFreq( newTunnel, myFreq ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -370,7 +370,7 @@ public abstract class PartP2PTunnel extends PartBasicSt public boolean onPartShiftActivate( EntityPlayer player, Vec3 pos ) { ItemStack is = player.inventory.getCurrentItem(); - if ( is != null && is.getItem() instanceof IMemoryCard ) + if( is != null && is.getItem() instanceof IMemoryCard ) { IMemoryCard mc = (IMemoryCard) is.getItem(); NBTTagCompound data = new NBTTagCompound(); @@ -379,14 +379,14 @@ public abstract class PartP2PTunnel extends PartBasicSt boolean wasOutput = this.output; this.output = false; - if ( wasOutput || this.freq == 0 ) + if( wasOutput || this.freq == 0 ) newFreq = System.currentTimeMillis(); try { this.proxy.getP2P().updateFreq( this, newFreq ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -430,7 +430,7 @@ public abstract class PartP2PTunnel extends PartBasicSt { this.proxy.getEnergy().extractAEPower( ae_to_tax, Actionable.MODULATE, PowerMultiplier.ONE ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } diff --git a/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java b/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java index 2f9f9deae..821818db9 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java +++ b/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java @@ -50,8 +50,8 @@ import appeng.me.helpers.AENetworkProxy; public class PartP2PTunnelME extends PartP2PTunnel implements IGridTickable { - final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", null, true ); public final Connections connection = new Connections( this ); + final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", null, true ); public PartP2PTunnelME( ItemStack is ) { @@ -60,13 +60,6 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I this.outerProxy.setFlags( GridFlags.DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED ); } - @Override - public void setPartHostInfo( ForgeDirection side, IPartHost host, TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side ) ); - } - @Override public void readFromNBT( NBTTagCompound extra ) { @@ -82,10 +75,26 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I } @Override - public void addToWorld() + public void onTunnelNetworkChange() { - super.addToWorld(); - this.outerProxy.onReady(); + super.onTunnelNetworkChange(); + if( !this.output ) + { + try + { + this.proxy.getTick().wakeDevice( this.proxy.getNode() ); + } + catch( GridAccessException e ) + { + // :P + } + } + } + + @Override + public AECableType getCableConnectionType( ForgeDirection dir ) + { + return AECableType.DENSE; } @Override @@ -95,6 +104,20 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I this.outerProxy.invalidate(); } + @Override + public void addToWorld() + { + super.addToWorld(); + this.outerProxy.onReady(); + } + + @Override + public void setPartHostInfo( ForgeDirection side, IPartHost host, TileEntity tile ) + { + super.setPartHostInfo( side, host, tile ); + this.outerProxy.setValidSides( EnumSet.of( side ) ); + } + @Override public IGridNode getExternalFacingNode() { @@ -102,26 +125,10 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I } @Override - public AECableType getCableConnectionType( ForgeDirection dir ) + public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) { - return AECableType.DENSE; - } - - @Override - public void onTunnelNetworkChange() - { - super.onTunnelNetworkChange(); - if ( !this.output ) - { - try - { - this.proxy.getTick().wakeDevice( this.proxy.getNode() ); - } - catch ( GridAccessException e ) - { - // :P - } - } + super.onPlacement( player, held, side ); + this.outerProxy.setOwner( player ); } @Override @@ -136,16 +143,16 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I // just move on... try { - if ( !this.proxy.getPath().isNetworkBooting() ) + if( !this.proxy.getPath().isNetworkBooting() ) { - if ( !this.proxy.getEnergy().isNetworkPowered() ) + if( !this.proxy.getEnergy().isNetworkPowered() ) { this.connection.markDestroy(); TickHandler.INSTANCE.addCallable( this.tile.getWorldObj(), this.connection ); } else { - if ( this.proxy.isActive() ) + if( this.proxy.isActive() ) { this.connection.markCreate(); TickHandler.INSTANCE.addCallable( this.tile.getWorldObj(), this.connection ); @@ -160,7 +167,7 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I return TickRateModulation.SLEEP; } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // meh? } @@ -168,43 +175,36 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I return TickRateModulation.IDLE; } - @Override - public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.outerProxy.setOwner( player ); - } - public void updateConnections( Connections connections ) { - if ( connections.destroy ) + if( connections.destroy ) { - for ( TunnelConnection cw : this.connection.connections.values() ) + for( TunnelConnection cw : this.connection.connections.values() ) cw.c.destroy(); this.connection.connections.clear(); } - else if ( connections.create ) + else if( connections.create ) { Iterator i = this.connection.connections.values().iterator(); - while ( i.hasNext() ) + while( i.hasNext() ) { TunnelConnection cw = i.next(); try { - if ( cw.tunnel.proxy.getGrid() != this.proxy.getGrid() ) + if( cw.tunnel.proxy.getGrid() != this.proxy.getGrid() ) { cw.c.destroy(); i.remove(); } - else if ( !cw.tunnel.proxy.isActive() ) + else if( !cw.tunnel.proxy.isActive() ) { cw.c.destroy(); i.remove(); } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -213,22 +213,21 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I LinkedList newSides = new LinkedList(); try { - for ( PartP2PTunnelME me : this.getOutputs() ) + for( PartP2PTunnelME me : this.getOutputs() ) { - if ( me.proxy.isActive() && connections.connections.get( me.getGridNode() ) == null ) + if( me.proxy.isActive() && connections.connections.get( me.getGridNode() ) == null ) { newSides.add( me ); } } - for ( PartP2PTunnelME me : newSides ) + for( PartP2PTunnelME me : newSides ) { try { - connections.connections.put( me.getGridNode(), - new TunnelConnection( me, AEApi.instance().createGridConnection( this.outerProxy.getNode(), me.outerProxy.getNode() ) ) ); + connections.connections.put( me.getGridNode(), new TunnelConnection( me, AEApi.instance().createGridConnection( this.outerProxy.getNode(), me.outerProxy.getNode() ) ) ); } - catch ( FailedConnection e ) + catch( FailedConnection e ) { final TileEntity start = this.getTile(); final TileEntity end = me.getTile(); @@ -237,7 +236,7 @@ public class PartP2PTunnelME extends PartP2PTunnel implements I } } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { AELog.error( e ); } diff --git a/src/main/java/appeng/parts/reporting/PartConversionMonitor.java b/src/main/java/appeng/parts/reporting/PartConversionMonitor.java index bd2aeccb7..24e133dae 100644 --- a/src/main/java/appeng/parts/reporting/PartConversionMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartConversionMonitor.java @@ -56,41 +56,41 @@ public class PartConversionMonitor extends PartStorageMonitor @Override public boolean onPartShiftActivate( EntityPlayer player, Vec3 pos ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; - if ( !this.proxy.isActive() ) + if( !this.proxy.isActive() ) return false; - if ( !Platform.hasPermissions( this.getLocation(), player ) ) + if( !Platform.hasPermissions( this.getLocation(), player ) ) return false; boolean ModeB = false; ItemStack item = player.getCurrentEquippedItem(); - if ( item == null && this.getDisplayed() != null ) + if( item == null && this.getDisplayed() != null ) { ModeB = true; item = ( (IAEItemStack) this.getDisplayed() ).getItemStack(); } - if ( item != null ) + if( item != null ) { try { - if ( !this.proxy.isActive() ) + if( !this.proxy.isActive() ) return false; IEnergySource energy = this.proxy.getEnergy(); IMEMonitor cell = this.proxy.getStorage().getItemInventory(); IAEItemStack input = AEItemStack.create( item ); - if ( ModeB ) + if( ModeB ) { - for ( int x = 0; x < player.inventory.getSizeInventory(); x++ ) + for( int x = 0; x < player.inventory.getSizeInventory(); x++ ) { ItemStack targetStack = player.inventory.getStackInSlot( x ); - if ( input.equals( targetStack ) ) + if( input.equals( targetStack ) ) { IAEItemStack insertItem = input.copy(); insertItem.setStackSize( targetStack.stackSize ); @@ -105,7 +105,7 @@ public class PartConversionMonitor extends PartStorageMonitor player.inventory.setInventorySlotContents( player.inventory.currentItem, failedToInsert == null ? null : failedToInsert.getItemStack() ); } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -117,11 +117,11 @@ public class PartConversionMonitor extends PartStorageMonitor protected void extractItem( EntityPlayer player ) { IAEItemStack input = (IAEItemStack) this.getDisplayed(); - if ( input != null ) + if( input != null ) { try { - if ( !this.proxy.isActive() ) + if( !this.proxy.isActive() ) return; IEnergySource energy = this.proxy.getEnergy(); @@ -131,23 +131,23 @@ public class PartConversionMonitor extends PartStorageMonitor input.setStackSize( is.getMaxStackSize() ); IAEItemStack retrieved = Platform.poweredExtraction( energy, cell, input, new PlayerSource( player, this ) ); - if ( retrieved != null ) + if( retrieved != null ) { ItemStack newItems = retrieved.getItemStack(); InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); newItems = adaptor.addItems( newItems ); - if ( newItems != null ) + if( newItems != null ) { TileEntity te = this.tile; List list = Collections.singletonList( newItems ); Platform.spawnDrops( player.worldObj, te.xCoord + this.side.offsetX, te.yCoord + this.side.offsetY, te.zCoord + this.side.offsetZ, list ); } - if ( player.openContainer != null ) + if( player.openContainer != null ) player.openContainer.detectAndSendChanges(); } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } diff --git a/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java b/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java index e2eb541f7..840d14bec 100644 --- a/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java @@ -53,8 +53,8 @@ public class PartCraftingTerminal extends PartTerminal { super.getDrops( drops, wrenched ); - for ( ItemStack is : this.craftingGrid ) - if ( is != null ) + for( ItemStack is : this.craftingGrid ) + if( is != null ) drops.add( is ); } @@ -78,14 +78,14 @@ public class PartCraftingTerminal extends PartTerminal int x = (int) p.posX; int y = (int) p.posY; int z = (int) p.posZ; - if ( this.getHost().getTile() != null ) + if( this.getHost().getTile() != null ) { x = this.tile.xCoord; y = this.tile.yCoord; z = this.tile.zCoord; } - if ( GuiBridge.GUI_CRAFTING_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.side, p ) ) + if( GuiBridge.GUI_CRAFTING_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.side, p ) ) return GuiBridge.GUI_CRAFTING_TERMINAL; return GuiBridge.GUI_ME; } @@ -99,7 +99,7 @@ public class PartCraftingTerminal extends PartTerminal @Override public IInventory getInventoryByName( String name ) { - if ( name.equals( "crafting" ) ) + if( name.equals( "crafting" ) ) return this.craftingGrid; return super.getInventoryByName( name ); } diff --git a/src/main/java/appeng/parts/reporting/PartDarkMonitor.java b/src/main/java/appeng/parts/reporting/PartDarkMonitor.java index 8d62ae2e6..800e49df8 100644 --- a/src/main/java/appeng/parts/reporting/PartDarkMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartDarkMonitor.java @@ -64,7 +64,7 @@ public class PartDarkMonitor extends PartMonitor rh.setBounds( 2, 2, 14, 14, 14, 16 ); rh.renderBlock( x, y, z, renderer ); - if ( this.getLightLevel() > 0 ) + if( this.getLightLevel() > 0 ) { int l = 13; Tessellator.instance.setBrightness( l << 20 | l << 4 ); diff --git a/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java b/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java index e57dd7d78..a48a9635e 100644 --- a/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java @@ -42,11 +42,11 @@ public class PartInterfaceTerminal extends PartMonitor @Override public boolean onPartActivate( EntityPlayer player, Vec3 pos ) { - if ( !super.onPartActivate( player, pos ) ) + if( !super.onPartActivate( player, pos ) ) { - if ( !player.isSneaking() ) + if( !player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( player, this.getHost().getTile(), this.side, GuiBridge.GUI_INTERFACE_TERMINAL ); diff --git a/src/main/java/appeng/parts/reporting/PartMonitor.java b/src/main/java/appeng/parts/reporting/PartMonitor.java index 1ff5fc5b8..78db32098 100644 --- a/src/main/java/appeng/parts/reporting/PartMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartMonitor.java @@ -18,6 +18,7 @@ package appeng.parts.reporting; + import java.io.IOException; import io.netty.buffer.ByteBuf; @@ -48,205 +49,67 @@ import appeng.me.GridAccessException; import appeng.parts.AEBasePart; import appeng.util.Platform; + public class PartMonitor extends AEBasePart implements IPartMonitor, IPowerChannelState { - // CableBusTextures frontSolid = CableBusTextures.PartMonitor_Solid; - CableBusTextures frontDark = CableBusTextures.PartMonitor_Colored; - CableBusTextures frontBright = CableBusTextures.PartMonitor_Bright; - CableBusTextures frontColored = CableBusTextures.PartMonitor_Colored; - - boolean notLightSource = !this.getClass().equals( PartMonitor.class ); - final int POWERED_FLAG = 4; final int BOOTING_FLAG = 8; final int CHANNEL_FLAG = 16; - + // CableBusTextures frontSolid = CableBusTextures.PartMonitor_Solid; + CableBusTextures frontDark = CableBusTextures.PartMonitor_Colored; + CableBusTextures frontBright = CableBusTextures.PartMonitor_Bright; + CableBusTextures frontColored = CableBusTextures.PartMonitor_Colored; + boolean notLightSource = !this.getClass().equals( PartMonitor.class ); byte spin = 0; // 0-3 int clientFlags = 0; // sent as byte. float opacity = -1; - @Override - public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) + public PartMonitor( ItemStack is ) { - super.onPlacement( player, held, side ); - - byte rotation = (byte) (MathHelper.floor_double( (player.rotationYaw * 4F) / 360F + 2.5D ) & 3); - if ( side == ForgeDirection.UP ) - this.spin = rotation; - else if ( side == ForgeDirection.DOWN ) - this.spin = rotation; - } - - @Override - public void writeToNBT(NBTTagCompound data) - { - super.writeToNBT( data ); - data.setFloat( "opacity", this.opacity ); - data.setByte( "spin", this.spin ); - } - - @Override - public void readFromNBT(NBTTagCompound data) - { - super.readFromNBT( data ); - if ( data.hasKey( "opacity" ) ) - this.opacity = data.getFloat( "opacity" ); - this.spin = data.getByte( "spin" ); - } - - @Override - public boolean onPartActivate(EntityPlayer player, Vec3 pos) - { - TileEntity te = this.getTile(); - - if ( !player.isSneaking() && Platform.isWrench( player, player.inventory.getCurrentItem(), te.xCoord, te.yCoord, te.zCoord ) ) - { - if ( Platform.isServer() ) - { - if ( this.spin > 3 ) - this.spin = 0; - - switch (this.spin) - { - case 0: - this.spin = 1; - break; - case 1: - this.spin = 3; - break; - case 2: - this.spin = 0; - break; - case 3: - this.spin = 2; - break; - } - - this.host.markForUpdate(); - this.saveChanges(); - } - return true; - } - else - return super.onPartActivate( player, pos ); - } - - @MENetworkEventSubscribe - public void bootingRender(MENetworkBootingStatusChange c) - { - if ( this.notLightSource ) - this.getHost().markForUpdate(); - } - - @Override - public void onNeighborChanged() - { - this.opacity = -1; - this.getHost().markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerRender(MENetworkPowerStatusChange c) - { - this.getHost().markForUpdate(); - } - - @Override - public void writeToStream(ByteBuf data) throws IOException - { - super.writeToStream( data ); - this.clientFlags = this.spin & 3; - - try - { - if ( this.proxy.getEnergy().isNetworkPowered() ) - this.clientFlags |= this.POWERED_FLAG; - - if ( this.proxy.getPath().isNetworkBooting() ) - this.clientFlags |= this.BOOTING_FLAG; - - if ( this.proxy.getNode().meetsChannelRequirements() ) - this.clientFlags |= this.CHANNEL_FLAG; - } - catch (GridAccessException e) - { - // um.. nothing. - } - - data.writeByte( (byte) this.clientFlags ); - } - - @Override - public boolean readFromStream(ByteBuf data) throws IOException - { - super.readFromStream( data ); - int oldFlags = this.clientFlags; - this.clientFlags = data.readByte(); - this.spin = (byte) (this.clientFlags & 3); - if ( this.clientFlags == oldFlags ) - return false; - return true; - } - - @Override - public int getLightLevel() - { - return this.blockLight( this.isPowered() ? (this.notLightSource ? 9 : 15) : 0 ); - } - - private int blockLight(int emit) - { - if ( this.opacity < 0 ) - { - TileEntity te = this.getTile(); - this.opacity = 255 - te.getWorldObj().getBlockLightOpacity( te.xCoord + this.side.offsetX, te.yCoord + this.side.offsetY, te.zCoord + this.side.offsetZ ); - } - - return (int) (emit * (this.opacity / 255.0f)); - } - - @Override - public boolean isPowered() - { - try - { - if ( Platform.isServer() ) - return this.proxy.getEnergy().isNetworkPowered(); - else - return ((this.clientFlags & this.POWERED_FLAG) == this.POWERED_FLAG); - } - catch (GridAccessException e) - { - return false; - } - } - - public PartMonitor(ItemStack is) { this( is, false ); } - protected PartMonitor(ItemStack is, boolean requireChannel) { + protected PartMonitor( ItemStack is, boolean requireChannel ) + { super( is ); - if ( requireChannel ) + if( requireChannel ) { this.proxy.setFlags( GridFlags.REQUIRE_CHANNEL ); this.proxy.setIdlePowerUsage( 1.0 / 2.0 ); } else this.proxy.setIdlePowerUsage( 1.0 / 16.0 ); // lights drain a little bit. + } + @MENetworkEventSubscribe + public void bootingRender( MENetworkBootingStatusChange c ) + { + if( this.notLightSource ) + this.getHost().markForUpdate(); + } + + @MENetworkEventSubscribe + public void powerRender( MENetworkPowerStatusChange c ) + { + this.getHost().markForUpdate(); } @Override - @SideOnly(Side.CLIENT) - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) + public void getBoxes( IPartCollisionHelper bch ) + { + bch.addBox( 2, 2, 14, 14, 14, 16 ); + bch.addBox( 4, 4, 13, 12, 12, 14 ); + } + + @Override + @SideOnly( Side.CLIENT ) + public void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ) { rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), - this.is.getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); + rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.is.getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); rh.renderInventoryBox( renderer ); rh.setInvColor( this.getColor().whiteVariant ); @@ -263,18 +126,17 @@ public class PartMonitor extends AEBasePart implements IPartMonitor, IPowerChann } @Override - @SideOnly(Side.CLIENT) - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) + @SideOnly( Side.CLIENT ) + public void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ) { this.renderCache = rh.useSimplifiedRendering( x, y, z, this, this.renderCache ); - rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), - this.is.getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); + rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.is.getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); rh.setBounds( 2, 2, 14, 14, 14, 16 ); rh.renderBlock( x, y, z, renderer ); - if ( this.getLightLevel() > 0 ) + if( this.getLightLevel() > 0 ) { int l = 13; Tessellator.instance.setBrightness( l << 20 | l << 4 ); @@ -293,28 +155,26 @@ public class PartMonitor extends AEBasePart implements IPartMonitor, IPowerChann renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - if ( this.notLightSource ) + if( this.notLightSource ) { - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), - CableBusTextures.PartMonitorBack.getIcon(), this.is.getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), - CableBusTextures.PartMonitorSidesStatus.getIcon() ); + rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.is.getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); } rh.setBounds( 4, 4, 13, 12, 12, 14 ); rh.renderBlock( x, y, z, renderer ); - if ( this.notLightSource ) + if( this.notLightSource ) { - boolean hasChan = (this.clientFlags & (this.POWERED_FLAG | this.CHANNEL_FLAG)) == (this.POWERED_FLAG | this.CHANNEL_FLAG); - boolean hasPower = (this.clientFlags & this.POWERED_FLAG) == this.POWERED_FLAG; + boolean hasChan = ( this.clientFlags & ( this.POWERED_FLAG | this.CHANNEL_FLAG ) ) == ( this.POWERED_FLAG | this.CHANNEL_FLAG ); + boolean hasPower = ( this.clientFlags & this.POWERED_FLAG ) == this.POWERED_FLAG; - if ( hasChan ) + if( hasChan ) { int l = 14; Tessellator.instance.setBrightness( l << 20 | l << 4 ); Tessellator.instance.setColorOpaque_I( this.getColor().blackVariant ); } - else if ( hasPower ) + else if( hasPower ) { int l = 9; Tessellator.instance.setBrightness( l << 20 | l << 4 ); @@ -331,23 +191,157 @@ public class PartMonitor extends AEBasePart implements IPartMonitor, IPowerChann rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.UP, renderer ); rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.DOWN, renderer ); } + } + private int blockLight( int emit ) + { + if( this.opacity < 0 ) + { + TileEntity te = this.getTile(); + this.opacity = 255 - te.getWorldObj().getBlockLightOpacity( te.xCoord + this.side.offsetX, te.yCoord + this.side.offsetY, te.zCoord + this.side.offsetZ ); + } + + return (int) ( emit * ( this.opacity / 255.0f ) ); } @Override - public void getBoxes(IPartCollisionHelper bch) + public boolean isPowered() { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 4, 4, 13, 12, 12, 14 ); + try + { + if( Platform.isServer() ) + return this.proxy.getEnergy().isNetworkPowered(); + else + return ( ( this.clientFlags & this.POWERED_FLAG ) == this.POWERED_FLAG ); + } + catch( GridAccessException e ) + { + return false; + } + } + + @Override + public void onNeighborChanged() + { + this.opacity = -1; + this.getHost().markForUpdate(); + } + + @Override + public void readFromNBT( NBTTagCompound data ) + { + super.readFromNBT( data ); + if( data.hasKey( "opacity" ) ) + this.opacity = data.getFloat( "opacity" ); + this.spin = data.getByte( "spin" ); + } + + @Override + public void writeToNBT( NBTTagCompound data ) + { + super.writeToNBT( data ); + data.setFloat( "opacity", this.opacity ); + data.setByte( "spin", this.spin ); + } + + @Override + public void writeToStream( ByteBuf data ) throws IOException + { + super.writeToStream( data ); + this.clientFlags = this.spin & 3; + + try + { + if( this.proxy.getEnergy().isNetworkPowered() ) + this.clientFlags |= this.POWERED_FLAG; + + if( this.proxy.getPath().isNetworkBooting() ) + this.clientFlags |= this.BOOTING_FLAG; + + if( this.proxy.getNode().meetsChannelRequirements() ) + this.clientFlags |= this.CHANNEL_FLAG; + } + catch( GridAccessException e ) + { + // um.. nothing. + } + + data.writeByte( (byte) this.clientFlags ); + } + + @Override + public boolean readFromStream( ByteBuf data ) throws IOException + { + super.readFromStream( data ); + int oldFlags = this.clientFlags; + this.clientFlags = data.readByte(); + this.spin = (byte) ( this.clientFlags & 3 ); + if( this.clientFlags == oldFlags ) + return false; + return true; + } + + @Override + public int getLightLevel() + { + return this.blockLight( this.isPowered() ? ( this.notLightSource ? 9 : 15 ) : 0 ); + } + + @Override + public boolean onPartActivate( EntityPlayer player, Vec3 pos ) + { + TileEntity te = this.getTile(); + + if( !player.isSneaking() && Platform.isWrench( player, player.inventory.getCurrentItem(), te.xCoord, te.yCoord, te.zCoord ) ) + { + if( Platform.isServer() ) + { + if( this.spin > 3 ) + this.spin = 0; + + switch( this.spin ) + { + case 0: + this.spin = 1; + break; + case 1: + this.spin = 3; + break; + case 2: + this.spin = 0; + break; + case 3: + this.spin = 2; + break; + } + + this.host.markForUpdate(); + this.saveChanges(); + } + return true; + } + else + return super.onPartActivate( player, pos ); + } + + @Override + public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) + { + super.onPlacement( player, held, side ); + + byte rotation = (byte) ( MathHelper.floor_double( ( player.rotationYaw * 4F ) / 360F + 2.5D ) & 3 ); + if( side == ForgeDirection.UP ) + this.spin = rotation; + else if( side == ForgeDirection.DOWN ) + this.spin = rotation; } @Override public boolean isActive() { - if ( this.notLightSource ) - return ((this.clientFlags & (this.CHANNEL_FLAG | this.POWERED_FLAG)) == (this.CHANNEL_FLAG | this.POWERED_FLAG)); + if( this.notLightSource ) + return ( ( this.clientFlags & ( this.CHANNEL_FLAG | this.POWERED_FLAG ) ) == ( this.CHANNEL_FLAG | this.POWERED_FLAG ) ); else return this.isPowered(); } - } diff --git a/src/main/java/appeng/parts/reporting/PartPatternTerminal.java b/src/main/java/appeng/parts/reporting/PartPatternTerminal.java index 161339438..523b4ec04 100644 --- a/src/main/java/appeng/parts/reporting/PartPatternTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartPatternTerminal.java @@ -57,21 +57,11 @@ public class PartPatternTerminal extends PartTerminal @Override public void getDrops( List drops, boolean wrenched ) { - for ( ItemStack is : this.pattern ) - if ( is != null ) + for( ItemStack is : this.pattern ) + if( is != null ) drops.add( is ); } - @Override - public void writeToNBT( NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "craftingMode", this.craftingMode ); - this.pattern.writeToNBT( data, "pattern" ); - this.output.writeToNBT( data, "outputList" ); - this.crafting.writeToNBT( data, "craftingGrid" ); - } - @Override public void readFromNBT( NBTTagCompound data ) { @@ -82,20 +72,30 @@ public class PartPatternTerminal extends PartTerminal this.crafting.readFromNBT( data, "craftingGrid" ); } + @Override + public void writeToNBT( NBTTagCompound data ) + { + super.writeToNBT( data ); + data.setBoolean( "craftingMode", this.craftingMode ); + this.pattern.writeToNBT( data, "pattern" ); + this.output.writeToNBT( data, "outputList" ); + this.crafting.writeToNBT( data, "craftingGrid" ); + } + @Override public GuiBridge getGui( EntityPlayer p ) { int x = (int) p.posX; int y = (int) p.posY; int z = (int) p.posZ; - if ( this.getHost().getTile() != null ) + if( this.getHost().getTile() != null ) { x = this.tile.xCoord; y = this.tile.yCoord; z = this.tile.zCoord; } - if ( GuiBridge.GUI_PATTERN_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.side, p ) ) + if( GuiBridge.GUI_PATTERN_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.side, p ) ) return GuiBridge.GUI_PATTERN_TERMINAL; return GuiBridge.GUI_ME; } @@ -103,24 +103,24 @@ public class PartPatternTerminal extends PartTerminal @Override public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) { - if ( inv == this.pattern && slot == 1 ) + if( inv == this.pattern && slot == 1 ) { ItemStack is = this.pattern.getStackInSlot( 1 ); - if ( is != null && is.getItem() instanceof ICraftingPatternItem ) + if( is != null && is.getItem() instanceof ICraftingPatternItem ) { ICraftingPatternItem pattern = (ICraftingPatternItem) is.getItem(); ICraftingPatternDetails details = pattern.getPatternForItem( is, this.getHost().getTile().getWorldObj() ); - if ( details != null ) + if( details != null ) { this.setCraftingRecipe( details.isCraftable() ); - for ( int x = 0; x < this.crafting.getSizeInventory() && x < details.getInputs().length; x++ ) + for( int x = 0; x < this.crafting.getSizeInventory() && x < details.getInputs().length; x++ ) { IAEItemStack item = details.getInputs()[x]; this.crafting.setInventorySlotContents( x, item == null ? null : item.getItemStack() ); } - for ( int x = 0; x < this.output.getSizeInventory() && x < details.getOutputs().length; x++ ) + for( int x = 0; x < this.output.getSizeInventory() && x < details.getOutputs().length; x++ ) { IAEItemStack item = details.getOutputs()[x]; this.output.setInventorySlotContents( x, item == null ? null : item.getItemStack() ); @@ -128,7 +128,7 @@ public class PartPatternTerminal extends PartTerminal } } } - else if ( inv == this.crafting ) + else if( inv == this.crafting ) { this.fixCraftingRecipes(); } @@ -138,12 +138,12 @@ public class PartPatternTerminal extends PartTerminal private void fixCraftingRecipes() { - if ( this.craftingMode ) + if( this.craftingMode ) { - for ( int x = 0; x < this.crafting.getSizeInventory(); x++ ) + for( int x = 0; x < this.crafting.getSizeInventory(); x++ ) { ItemStack is = this.crafting.getStackInSlot( x ); - if ( is != null ) + if( is != null ) is.stackSize = 1; } } @@ -163,13 +163,13 @@ public class PartPatternTerminal extends PartTerminal @Override public IInventory getInventoryByName( String name ) { - if ( name.equals( "crafting" ) ) + if( name.equals( "crafting" ) ) return this.crafting; - if ( name.equals( "output" ) ) + if( name.equals( "output" ) ) return this.output; - if ( name.equals( "pattern" ) ) + if( name.equals( "pattern" ) ) return this.pattern; return super.getInventoryByName( name ); diff --git a/src/main/java/appeng/parts/reporting/PartSemiDarkMonitor.java b/src/main/java/appeng/parts/reporting/PartSemiDarkMonitor.java index ce0903a7c..b803d835b 100644 --- a/src/main/java/appeng/parts/reporting/PartSemiDarkMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartSemiDarkMonitor.java @@ -67,7 +67,7 @@ public class PartSemiDarkMonitor extends PartMonitor rh.setBounds( 2, 2, 14, 14, 14, 16 ); rh.renderBlock( x, y, z, renderer ); - if ( this.getLightLevel() > 0 ) + if( this.getLightLevel() > 0 ) { int l = 13; Tessellator.instance.setBrightness( l << 20 | l << 4 ); diff --git a/src/main/java/appeng/parts/reporting/PartStorageMonitor.java b/src/main/java/appeng/parts/reporting/PartStorageMonitor.java index 28cf98a98..bf2cc2341 100644 --- a/src/main/java/appeng/parts/reporting/PartStorageMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartStorageMonitor.java @@ -86,6 +86,17 @@ public class PartStorageMonitor extends PartMonitor implements IPartStorageMonit // frontSolid = CableBusTextures.PartStorageMonitor_Solid; } + @Override + public void readFromNBT( NBTTagCompound data ) + { + super.readFromNBT( data ); + + this.isLocked = data.getBoolean( "isLocked" ); + + NBTTagCompound myItem = data.getCompoundTag( "configuredItem" ); + this.configuredItem = AEItemStack.loadItemStackFromNBT( myItem ); + } + @Override public void writeToNBT( NBTTagCompound data ) { @@ -101,14 +112,33 @@ public class PartStorageMonitor extends PartMonitor implements IPartStorageMonit } @Override - public void readFromNBT( NBTTagCompound data ) + public void writeToStream( ByteBuf data ) throws IOException { - super.readFromNBT( data ); + super.writeToStream( data ); - this.isLocked = data.getBoolean( "isLocked" ); + data.writeByte( this.spin ); + data.writeBoolean( this.isLocked ); + data.writeBoolean( this.configuredItem != null ); + if( this.configuredItem != null ) + this.configuredItem.writeToPacket( data ); + } - NBTTagCompound myItem = data.getCompoundTag( "configuredItem" ); - this.configuredItem = AEItemStack.loadItemStackFromNBT( myItem ); + @Override + public boolean readFromStream( ByteBuf data ) throws IOException + { + boolean stuff = super.readFromStream( data ); + + this.spin = data.readByte(); + this.isLocked = data.readBoolean(); + boolean val = data.readBoolean(); + if( val ) + this.configuredItem = AEItemStack.loadItemStackFromPacket( data ); + else + this.configuredItem = null; + + this.updateList = true; + + return stuff; } @Override @@ -143,36 +173,6 @@ public class PartStorageMonitor extends PartMonitor implements IPartStorageMonit return true; } - @Override - public void writeToStream( ByteBuf data ) throws IOException - { - super.writeToStream( data ); - - data.writeByte( this.spin ); - data.writeBoolean( this.isLocked ); - data.writeBoolean( this.configuredItem != null ); - if( this.configuredItem != null ) - this.configuredItem.writeToPacket( data ); - } - - @Override - public boolean readFromStream( ByteBuf data ) throws IOException - { - boolean stuff = super.readFromStream( data ); - - this.spin = data.readByte(); - this.isLocked = data.readBoolean(); - boolean val = data.readBoolean(); - if( val ) - this.configuredItem = AEItemStack.loadItemStackFromPacket( data ); - else - this.configuredItem = null; - - this.updateList = true; - - return stuff; - } - // update the system... public void configureWatchers() { diff --git a/src/main/java/appeng/parts/reporting/PartTerminal.java b/src/main/java/appeng/parts/reporting/PartTerminal.java index 332668952..17c18208b 100644 --- a/src/main/java/appeng/parts/reporting/PartTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartTerminal.java @@ -71,8 +71,8 @@ public class PartTerminal extends PartMonitor implements ITerminalHost, IConfigM { super.getDrops( drops, wrenched ); - for ( ItemStack is : this.viewCell ) - if ( is != null ) + for( ItemStack is : this.viewCell ) + if( is != null ) drops.add( is ); } @@ -82,14 +82,6 @@ public class PartTerminal extends PartMonitor implements ITerminalHost, IConfigM return this.cm; } - @Override - public void writeToNBT( NBTTagCompound data ) - { - super.writeToNBT( data ); - this.cm.writeToNBT( data ); - this.viewCell.writeToNBT( data, "viewCell" ); - } - @Override public void readFromNBT( NBTTagCompound data ) { @@ -98,14 +90,22 @@ public class PartTerminal extends PartMonitor implements ITerminalHost, IConfigM this.viewCell.readFromNBT( data, "viewCell" ); } + @Override + public void writeToNBT( NBTTagCompound data ) + { + super.writeToNBT( data ); + this.cm.writeToNBT( data ); + this.viewCell.writeToNBT( data, "viewCell" ); + } + @Override public boolean onPartActivate( EntityPlayer player, Vec3 pos ) { - if ( !super.onPartActivate( player, pos ) ) + if( !super.onPartActivate( player, pos ) ) { - if ( !player.isSneaking() ) + if( !player.isSneaking() ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return true; Platform.openGUI( player, this.getHost().getTile(), this.side, this.getGui( player ) ); @@ -128,7 +128,7 @@ public class PartTerminal extends PartMonitor implements ITerminalHost, IConfigM { return this.proxy.getStorage().getItemInventory(); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // err nope? } @@ -142,7 +142,7 @@ public class PartTerminal extends PartMonitor implements ITerminalHost, IConfigM { return this.proxy.getStorage().getFluidInventory(); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // err nope? } diff --git a/src/main/java/appeng/recipes/AEItemResolver.java b/src/main/java/appeng/recipes/AEItemResolver.java index d849e8a54..f02f204e4 100644 --- a/src/main/java/appeng/recipes/AEItemResolver.java +++ b/src/main/java/appeng/recipes/AEItemResolver.java @@ -45,90 +45,90 @@ public class AEItemResolver implements ISubItemResolver public Object resolveItemByName( String nameSpace, String itemName ) { - if ( nameSpace.equals( AppEng.MOD_ID ) ) + if( nameSpace.equals( AppEng.MOD_ID ) ) { final IDefinitions definitions = AEApi.instance().definitions(); final IItems items = definitions.items(); final IParts parts = definitions.parts(); - if ( itemName.startsWith( "PaintBall." ) ) + if( itemName.startsWith( "PaintBall." ) ) { return this.paintBall( items.coloredPaintBall(), itemName.substring( itemName.indexOf( '.' ) + 1 ), false ); } - if ( itemName.startsWith( "LumenPaintBall." ) ) + if( itemName.startsWith( "LumenPaintBall." ) ) { return this.paintBall( items.coloredLumenPaintBall(), itemName.substring( itemName.indexOf( '.' ) + 1 ), true ); } - if ( itemName.equals( "CableGlass" ) ) + if( itemName.equals( "CableGlass" ) ) { return new ResolverResultSet( "CableGlass", parts.cableGlass().allStacks( 1 ) ); } - if ( itemName.startsWith( "CableGlass." ) ) + if( itemName.startsWith( "CableGlass." ) ) { return this.cableItem( parts.cableGlass(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); } - if ( itemName.equals( "CableCovered" ) ) + if( itemName.equals( "CableCovered" ) ) { return new ResolverResultSet( "CableCovered", parts.cableCovered().allStacks( 1 ) ); } - if ( itemName.startsWith( "CableCovered." ) ) + if( itemName.startsWith( "CableCovered." ) ) { return this.cableItem( parts.cableCovered(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); } - if ( itemName.equals( "CableSmart" ) ) + if( itemName.equals( "CableSmart" ) ) { return new ResolverResultSet( "CableSmart", parts.cableSmart().allStacks( 1 ) ); } - if ( itemName.startsWith( "CableSmart." ) ) + if( itemName.startsWith( "CableSmart." ) ) { return this.cableItem( parts.cableSmart(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); } - if ( itemName.equals( "CableDense" ) ) + if( itemName.equals( "CableDense" ) ) { return new ResolverResultSet( "CableDense", parts.cableDense().allStacks( 1 ) ); } - if ( itemName.startsWith( "CableDense." ) ) + if( itemName.startsWith( "CableDense." ) ) { return this.cableItem( parts.cableDense(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); } - if ( itemName.startsWith( "ItemCrystalSeed." ) ) + if( itemName.startsWith( "ItemCrystalSeed." ) ) { - if ( itemName.equalsIgnoreCase( "ItemCrystalSeed.Certus" ) ) + if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Certus" ) ) return ItemCrystalSeed.getResolver( ItemCrystalSeed.Certus ); - if ( itemName.equalsIgnoreCase( "ItemCrystalSeed.Nether" ) ) + if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Nether" ) ) return new ResolverResult( "ItemCrystalSeed", ItemCrystalSeed.Nether ); - if ( itemName.equalsIgnoreCase( "ItemCrystalSeed.Fluix" ) ) + if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Fluix" ) ) return new ResolverResult( "ItemCrystalSeed", ItemCrystalSeed.Fluix ); return null; } - if ( itemName.startsWith( "ItemMaterial." ) ) + if( itemName.startsWith( "ItemMaterial." ) ) { String materialName = itemName.substring( itemName.indexOf( '.' ) + 1 ); MaterialType mt = MaterialType.valueOf( materialName ); // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); - if ( mt.itemInstance == ItemMultiMaterial.instance && mt.damageValue >= 0 && mt.isRegistered() ) + if( mt.itemInstance == ItemMultiMaterial.instance && mt.damageValue >= 0 && mt.isRegistered() ) return new ResolverResult( "ItemMultiMaterial", mt.damageValue ); } - if ( itemName.startsWith( "ItemPart." ) ) + if( itemName.startsWith( "ItemPart." ) ) { String partName = itemName.substring( itemName.indexOf( '.' ) + 1 ); PartType pt = PartType.valueOf( partName ); // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); int dVal = ItemMultiPart.instance.getDamageByType( pt ); - if ( dVal >= 0 ) + if( dVal >= 0 ) return new ResolverResult( "ItemMultiPart", dVal ); } } @@ -144,12 +144,12 @@ public class AEItemResolver implements ISubItemResolver { col = AEColor.valueOf( substring ); } - catch ( Throwable t ) + catch( Throwable t ) { col = AEColor.Transparent; } - if ( col == AEColor.Transparent ) + if( col == AEColor.Transparent ) return null; ItemStack is = partType.stack( col, 1 ); @@ -164,7 +164,7 @@ public class AEItemResolver implements ISubItemResolver { col = AEColor.valueOf( substring ); } - catch ( Throwable t ) + catch( Throwable t ) { col = AEColor.Transparent; } diff --git a/src/main/java/appeng/recipes/GroupIngredient.java b/src/main/java/appeng/recipes/GroupIngredient.java index 23819a11b..639f94b11 100644 --- a/src/main/java/appeng/recipes/GroupIngredient.java +++ b/src/main/java/appeng/recipes/GroupIngredient.java @@ -18,6 +18,7 @@ package appeng.recipes; + import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -30,45 +31,35 @@ import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; + public class GroupIngredient implements IIngredient { - int qty = 0; final String name; final List ingredients; + int qty = 0; ItemStack[] baked; boolean isInside = false; - public GroupIngredient(String myName, List ingredients) throws RecipeError { + public GroupIngredient( String myName, List ingredients ) throws RecipeError + { this.name = myName; - for (IIngredient I : ingredients) - if ( I.isAir() ) + for( IIngredient I : ingredients ) + if( I.isAir() ) throw new RecipeError( "Cannot include air in a group." ); this.ingredients = ingredients; } - public IIngredient copy(int qty) throws RecipeError + public IIngredient copy( int qty ) throws RecipeError { GroupIngredient gi = new GroupIngredient( this.name, this.ingredients ); gi.qty = qty; return gi; } - @Override - public int getDamageValue() - { - return OreDictionary.WILDCARD_VALUE; - } - - @Override - public String getItemName() - { - return this.name; - } - @Override public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { @@ -78,23 +69,23 @@ public class GroupIngredient implements IIngredient @Override public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError { - if ( this.baked != null ) + if( this.baked != null ) return this.baked; - if ( this.isInside ) + if( this.isInside ) return new ItemStack[0]; List out = new LinkedList(); this.isInside = true; try { - for (IIngredient i : this.ingredients) + for( IIngredient i : this.ingredients ) { try { out.addAll( Arrays.asList( i.getItemStackSet() ) ); } - catch (MissingIngredientError mir) + catch( MissingIngredientError mir ) { // oh well this is a group! } @@ -105,38 +96,49 @@ public class GroupIngredient implements IIngredient this.isInside = false; } - if ( out.size() == 0 ) + if( out.size() == 0 ) throw new MissingIngredientError( this.toString() + " - group could not be resolved to any items." ); - for (ItemStack is : out) + for( ItemStack is : out ) is.stackSize = this.qty; return out.toArray( new ItemStack[out.size()] ); } - @Override - public String getNameSpace() - { - return ""; - } - - @Override - public int getQty() - { - return 0; - } - @Override public boolean isAir() { return false; } + @Override + public String getNameSpace() + { + return ""; + } + + @Override + public String getItemName() + { + return this.name; + } + + @Override + public int getDamageValue() + { + return OreDictionary.WILDCARD_VALUE; + } + + @Override + public int getQty() + { + return 0; + } + @Override public void bake() throws RegistrationError, MissingIngredientError { this.baked = null; this.baked = this.getItemStackSet(); } - } diff --git a/src/main/java/appeng/recipes/Ingredient.java b/src/main/java/appeng/recipes/Ingredient.java index 050c07a23..8984a028a 100644 --- a/src/main/java/appeng/recipes/Ingredient.java +++ b/src/main/java/appeng/recipes/Ingredient.java @@ -37,6 +37,7 @@ import appeng.api.recipes.IIngredient; import appeng.api.recipes.ResolverResult; import appeng.api.recipes.ResolverResultSet; + public class Ingredient implements IIngredient { @@ -45,18 +46,17 @@ public class Ingredient implements IIngredient final public String nameSpace; final public String itemName; final public int meta; - NBTTagCompound nbt = null; - final public int qty; - + NBTTagCompound nbt = null; ItemStack[] baked; - public Ingredient(RecipeHandler handler, String input, int qty) throws RecipeError, MissedIngredientSet { + public Ingredient( RecipeHandler handler, String input, int qty ) throws RecipeError, MissedIngredientSet + { // works no matter wat! this.qty = qty; - if ( input.equals( "_" ) ) + if( input.equals( "_" ) ) { this.isAir = true; this.nameSpace = ""; @@ -67,18 +67,18 @@ public class Ingredient implements IIngredient this.isAir = false; String[] parts = input.split( ":" ); - if ( parts.length >= 2 ) + if( parts.length >= 2 ) { this.nameSpace = handler.alias( parts[0] ); String tmpName = handler.alias( parts[1] ); - if ( parts.length != 3 ) + if( parts.length != 3 ) { int sel = 0; - if ( this.nameSpace.equals( "oreDictionary" ) ) + if( this.nameSpace.equals( "oreDictionary" ) ) { - if ( parts.length == 3 ) + if( parts.length == 3 ) throw new RecipeError( "Cannot specify meta when using ore dictionary." ); sel = OreDictionary.WILDCARD_VALUE; } @@ -87,19 +87,19 @@ public class Ingredient implements IIngredient try { Object ro = AEApi.instance().registries().recipes().resolveItem( this.nameSpace, tmpName ); - if ( ro instanceof ResolverResult ) + if( ro instanceof ResolverResult ) { ResolverResult rr = (ResolverResult) ro; tmpName = rr.itemName; sel = rr.damageValue; this.nbt = rr.compound; } - else if ( ro instanceof ResolverResultSet ) + else if( ro instanceof ResolverResultSet ) { throw new MissedIngredientSet( (ResolverResultSet) ro ); } } - catch (IllegalArgumentException e) + catch( IllegalArgumentException e ) { throw new RecipeError( tmpName + " is not a valid ae2 item definition." ); } @@ -109,7 +109,7 @@ public class Ingredient implements IIngredient } else { - if ( parts[2].equals( "*" ) ) + if( parts[2].equals( "*" ) ) { this.meta = OreDictionary.WILDCARD_VALUE; } @@ -119,7 +119,7 @@ public class Ingredient implements IIngredient { this.meta = Integer.parseInt( parts[2] ); } - catch (NumberFormatException e) + catch( NumberFormatException e ) { throw new RecipeError( "Invalid Metadata." ); } @@ -133,31 +133,37 @@ public class Ingredient implements IIngredient handler.data.knownItem.add( this.toString() ); } + @Override + public String toString() + { + return this.nameSpace + ':' + this.itemName + ':' + this.meta; + } + @Override public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { - if ( this.isAir ) + if( this.isAir ) throw new RegistrationError( "Found blank item and expected a real item." ); - if ( this.nameSpace.equalsIgnoreCase( "oreDictionary" ) ) + if( this.nameSpace.equalsIgnoreCase( "oreDictionary" ) ) throw new RegistrationError( "Recipe format expected a single item, but got a set of items." ); Block blk = GameRegistry.findBlock( this.nameSpace, this.itemName ); - if ( blk == null ) + if( blk == null ) blk = GameRegistry.findBlock( this.nameSpace, "tile." + this.itemName ); - if ( blk != null ) + if( blk != null ) { Item it = Item.getItemFromBlock( blk ); - if ( it != null ) + if( it != null ) return this.MakeItemStack( it, this.qty, this.meta, this.nbt ); } Item it = GameRegistry.findItem( this.nameSpace, this.itemName ); - if ( it == null ) + if( it == null ) it = GameRegistry.findItem( this.nameSpace, "item." + this.itemName ); - if ( it != null ) + if( it != null ) return this.MakeItemStack( it, this.qty, this.meta, this.nbt ); /* @@ -176,39 +182,33 @@ public class Ingredient implements IIngredient throw new MissingIngredientError( "Unable to find item: " + this.toString() ); } - private ItemStack MakeItemStack(Item it, int quantity, int damageValue, NBTTagCompound compound) + private ItemStack MakeItemStack( Item it, int quantity, int damageValue, NBTTagCompound compound ) { ItemStack is = new ItemStack( it, quantity, damageValue ); is.setTagCompound( compound ); return is; } - @Override - public String toString() - { - return this.nameSpace + ':' + this.itemName + ':' + this.meta; - } - @Override public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError { - if ( this.baked != null ) + if( this.baked != null ) return this.baked; - if ( this.nameSpace.equalsIgnoreCase( "oreDictionary" ) ) + if( this.nameSpace.equalsIgnoreCase( "oreDictionary" ) ) { List ores = OreDictionary.getOres( this.itemName ); ItemStack[] set = ores.toArray( new ItemStack[ores.size()] ); // clone and set qty. - for (int x = 0; x < set.length; x++) + for( int x = 0; x < set.length; x++ ) { ItemStack is = set[x].copy(); is.stackSize = this.qty; set[x] = is; } - if ( set.length == 0 ) + if( set.length == 0 ) throw new MissingIngredientError( this.itemName + " - ore dictionary could not be resolved to any items." ); return set; @@ -253,5 +253,4 @@ public class Ingredient implements IIngredient this.baked = null; this.baked = this.getItemStackSet(); } - } diff --git a/src/main/java/appeng/recipes/IngredientSet.java b/src/main/java/appeng/recipes/IngredientSet.java index ef6c6dfe1..5023b0e1c 100644 --- a/src/main/java/appeng/recipes/IngredientSet.java +++ b/src/main/java/appeng/recipes/IngredientSet.java @@ -18,6 +18,7 @@ package appeng.recipes; + import java.util.LinkedList; import java.util.List; @@ -29,33 +30,22 @@ import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; import appeng.api.recipes.ResolverResultSet; + public class IngredientSet implements IIngredient { final int qty = 0; final String name; final List items; + final boolean isInside = false; ItemStack[] baked; - public IngredientSet(ResolverResultSet rr) { + public IngredientSet( ResolverResultSet rr ) + { this.name = rr.name; this.items = rr.results; } - final boolean isInside = false; - - @Override - public int getDamageValue() - { - return OreDictionary.WILDCARD_VALUE; - } - - @Override - public String getItemName() - { - return this.name; - } - @Override public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { @@ -65,47 +55,58 @@ public class IngredientSet implements IIngredient @Override public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError { - if ( this.baked != null ) + if( this.baked != null ) return this.baked; - if ( this.isInside ) + if( this.isInside ) return new ItemStack[0]; List out = new LinkedList(); out.addAll( this.items ); - if ( out.size() == 0 ) + if( out.size() == 0 ) throw new MissingIngredientError( this.toString() + " - group could not be resolved to any items." ); - for (ItemStack is : out) + for( ItemStack is : out ) is.stackSize = this.qty; return out.toArray( new ItemStack[out.size()] ); } - @Override - public String getNameSpace() - { - return ""; - } - - @Override - public int getQty() - { - return 0; - } - @Override public boolean isAir() { return false; } + @Override + public String getNameSpace() + { + return ""; + } + + @Override + public String getItemName() + { + return this.name; + } + + @Override + public int getDamageValue() + { + return OreDictionary.WILDCARD_VALUE; + } + + @Override + public int getQty() + { + return 0; + } + @Override public void bake() throws RegistrationError, MissingIngredientError { this.baked = null; this.baked = this.getItemStackSet(); } - } diff --git a/src/main/java/appeng/recipes/MissedIngredientSet.java b/src/main/java/appeng/recipes/MissedIngredientSet.java index d40b20eeb..2a5a9aa50 100644 --- a/src/main/java/appeng/recipes/MissedIngredientSet.java +++ b/src/main/java/appeng/recipes/MissedIngredientSet.java @@ -18,16 +18,18 @@ package appeng.recipes; + import appeng.api.recipes.ResolverResultSet; + public class MissedIngredientSet extends Throwable { private static final long serialVersionUID = 2672951714376345807L; final ResolverResultSet rrs; - public MissedIngredientSet(ResolverResultSet ro) { + public MissedIngredientSet( ResolverResultSet ro ) + { this.rrs = ro; } - } diff --git a/src/main/java/appeng/recipes/RecipeData.java b/src/main/java/appeng/recipes/RecipeData.java index 7143a5e16..6a7a56cb1 100644 --- a/src/main/java/appeng/recipes/RecipeData.java +++ b/src/main/java/appeng/recipes/RecipeData.java @@ -18,6 +18,7 @@ package appeng.recipes; + import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; @@ -26,6 +27,7 @@ import java.util.Set; import appeng.api.recipes.ICraftHandler; + public class RecipeData { @@ -33,11 +35,8 @@ public class RecipeData final public HashMap groups = new HashMap(); final public List Handlers = new LinkedList(); - + public final Set knownItem = new HashSet(); public boolean crash = true; public boolean exceptions = true; public boolean errorOnMissing = true; - - public final Set knownItem = new HashSet(); - } diff --git a/src/main/java/appeng/recipes/RecipeHandler.java b/src/main/java/appeng/recipes/RecipeHandler.java index 90e5b2cd9..fb14e1df3 100644 --- a/src/main/java/appeng/recipes/RecipeHandler.java +++ b/src/main/java/appeng/recipes/RecipeHandler.java @@ -62,191 +62,44 @@ import appeng.items.parts.ItemMultiPart; import appeng.recipes.handlers.IWebsiteSerializer; import appeng.recipes.handlers.OreRegistration; + public class RecipeHandler implements IRecipeHandler { final public List tokens = new LinkedList(); final RecipeData data; - public RecipeHandler() { + public RecipeHandler() + { this.data = new RecipeData(); } - RecipeHandler(RecipeHandler parent) { + RecipeHandler( RecipeHandler parent ) + { this.data = parent.data; } - private void addCrafting(ICraftHandler ch) + private void addCrafting( ICraftHandler ch ) { this.data.Handlers.add( ch ); } - public List findRecipe(ItemStack output) - { - List out = new LinkedList(); - - for (ICraftHandler ch : this.data.Handlers) - { - try - { - if ( ch instanceof IWebsiteSerializer && ((IWebsiteSerializer) ch).canCraft( output ) ) - { - out.add( (IWebsiteSerializer) ch ); - } - } - catch (Throwable t) - { - AELog.error( t ); - } - } - - return out; - } - - @Override - public void injectRecipes() - { - if ( cpw.mods.fml.common.Loader.instance().hasReachedState( LoaderState.POSTINITIALIZATION ) ) - throw new RuntimeException( "Recipes must now be loaded in Init." ); - - HashMap processed = new HashMap(); - try - { - for (ICraftHandler ch : this.data.Handlers) - { - try - { - ch.register(); - - Class clz = ch.getClass(); - Integer i = processed.get( clz ); - if ( i == null ) - processed.put( clz, 1 ); - else - processed.put( clz, i + 1 ); - } - catch (RegistrationError e) - { - AELog.warning( "Unable to register a recipe: " + e.getMessage() ); - if ( this.data.exceptions ) - AELog.error( e ); - if ( this.data.crash ) - throw e; - } - catch (MissingIngredientError e) - { - if ( this.data.errorOnMissing ) - { - AELog.warning( "Unable to register a recipe:" + e.getMessage() ); - if ( this.data.exceptions ) - AELog.error( e ); - if ( this.data.crash ) - throw e; - } - } - } - } - catch (Throwable e) - { - if ( this.data.exceptions ) - AELog.error( e ); - if ( this.data.crash ) - throw new RuntimeException( e ); - } - - for (Entry e : processed.entrySet()) - { - AELog.info( "Recipes Loading: " + e.getKey().getSimpleName() + ": " + e.getValue() + " loaded." ); - } - - if ( AEConfig.instance.isFeatureEnabled( AEFeature.WebsiteRecipes ) ) - { - try - { - ZipOutputStream out = new ZipOutputStream( new FileOutputStream( "recipes.zip" ) ); - - HashMultimap combined = HashMultimap.create(); - - for (String s : this.data.knownItem) - { - try - { - - Ingredient i = new Ingredient( this, s, 1 ); - - for (ItemStack is : i.getItemStackSet()) - { - String realName = this.getName( is ); - List recipes = this.findRecipe( is ); - if ( !recipes.isEmpty() ) - combined.putAll( realName, recipes ); - } - - } - catch (RecipeError ignored) - { - - } - catch (MissedIngredientSet ignored) - { - - } - catch (RegistrationError ignored) - { - - } - catch (MissingIngredientError ignored) - { - - } - } - - for (String realName : combined.keySet()) - { - int offset = 0; - - for (IWebsiteSerializer ws : combined.get( realName )) - { - String rew = ws.getPattern( this ); - if ( rew != null && rew.length() > 0 ) - { - out.putNextEntry( new ZipEntry( realName + '_' + offset + ".txt" ) ); - offset++; - out.write( rew.getBytes() ); - } - } - } - - out.close(); - } - catch (FileNotFoundException e1) - { - AELog.error( e1 ); - } - catch (IOException e1) - { - AELog.error( e1 ); - } - - } - } - - public String getName(IIngredient i) + public String getName( IIngredient i ) { try { - for (ItemStack is : i.getItemStackSet()) + for( ItemStack is : i.getItemStackSet() ) { try { return this.getName( is ); } - catch (RecipeError ignored) + catch( RecipeError ignored ) { } } } - catch (Throwable t) + catch( Throwable t ) { t.printStackTrace(); // :P @@ -255,12 +108,12 @@ public class RecipeHandler implements IRecipeHandler return i.getNameSpace() + ':' + i.getItemName(); } - public String getName(ItemStack is) throws RecipeError + public String getName( ItemStack is ) throws RecipeError { UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); String realName = id.modId + ':' + id.name; - if ( !id.modId.equals( AppEng.MOD_ID ) && !id.modId.equals( "minecraft" ) ) + if( !id.modId.equals( AppEng.MOD_ID ) && !id.modId.equals( "minecraft" ) ) throw new RecipeError( "Not applicable for website" ); final IDefinitions definitions = AEApi.instance().definitions(); @@ -273,97 +126,96 @@ public class RecipeHandler implements IRecipeHandler final Optional maybeCraftingUnitItem = blocks.craftingUnit().maybeItem(); final Optional maybeSkyChestItem = blocks.skyChest().maybeItem(); - if ( maybeCrystalSeedItem.isPresent() && is.getItem() == maybeCrystalSeedItem.get() ) + if( maybeCrystalSeedItem.isPresent() && is.getItem() == maybeCrystalSeedItem.get() ) { int dmg = is.getItemDamage(); - if ( dmg < ItemCrystalSeed.Nether ) + if( dmg < ItemCrystalSeed.Nether ) realName += ".Certus"; - else if ( dmg < ItemCrystalSeed.Fluix ) + else if( dmg < ItemCrystalSeed.Fluix ) realName += ".Nether"; - else if ( dmg < ItemCrystalSeed.END ) + else if( dmg < ItemCrystalSeed.END ) realName += ".Fluix"; } - else if ( maybeSkyStoneItem.isPresent() && is.getItem() == maybeSkyStoneItem.get() ) + else if( maybeSkyStoneItem.isPresent() && is.getItem() == maybeSkyStoneItem.get() ) { - switch (is.getItemDamage()) + switch( is.getItemDamage() ) { - case 1: - realName += ".Block"; - break; - case 2: - realName += ".Brick"; - break; - case 3: - realName += ".SmallBrick"; - break; - default: + case 1: + realName += ".Block"; + break; + case 2: + realName += ".Brick"; + break; + case 3: + realName += ".SmallBrick"; + break; + default: } } - else if ( maybeCraftingStorageItem.isPresent() && is.getItem() == maybeCraftingStorageItem.get() ) + else if( maybeCraftingStorageItem.isPresent() && is.getItem() == maybeCraftingStorageItem.get() ) { - switch (is.getItemDamage()) + switch( is.getItemDamage() ) { - case 1: - realName += "4k"; - break; - case 2: - realName += "16k"; - break; - case 3: - realName += "64k"; - break; - default: + case 1: + realName += "4k"; + break; + case 2: + realName += "16k"; + break; + case 3: + realName += "64k"; + break; + default: } } - else if ( maybeCraftingUnitItem.isPresent() && is.getItem() == maybeCraftingUnitItem.get() ) + else if( maybeCraftingUnitItem.isPresent() && is.getItem() == maybeCraftingUnitItem.get() ) { - switch (is.getItemDamage()) + switch( is.getItemDamage() ) { - case 1: - realName = realName.replace( "Unit", "Accelerator" ); - break; - default: + case 1: + realName = realName.replace( "Unit", "Accelerator" ); + break; + default: } } - else if ( maybeSkyChestItem.isPresent() && is.getItem() == maybeSkyChestItem.get() ) + else if( maybeSkyChestItem.isPresent() && is.getItem() == maybeSkyChestItem.get() ) { - switch (is.getItemDamage()) + switch( is.getItemDamage() ) { - case 1: - realName += ".Block"; - break; - default: + case 1: + realName += ".Block"; + break; + default: } } - else if ( is.getItem() instanceof ItemMultiMaterial ) + else if( is.getItem() instanceof ItemMultiMaterial ) { realName = realName.replace( "ItemMultiMaterial", "ItemMaterial" ); - realName += '.' + ((ItemMultiMaterial) is.getItem()).getTypeByStack( is ).name(); + realName += '.' + ( (ItemMultiMaterial) is.getItem() ).getTypeByStack( is ).name(); } - else if ( is.getItem() instanceof ItemMultiPart ) + else if( is.getItem() instanceof ItemMultiPart ) { realName = realName.replace( "ItemMultiPart", "ItemPart" ); - realName += '.' + ((ItemMultiPart) is.getItem()).getTypeByStack( is ).name(); + realName += '.' + ( (ItemMultiPart) is.getItem() ).getTypeByStack( is ).name(); } - else if ( is.getItemDamage() > 0 ) + else if( is.getItemDamage() > 0 ) realName += "." + is.getItemDamage(); return realName; - } - public String alias(String in) + public String alias( String in ) { String out = this.data.aliases.get( in ); - if ( out != null ) + if( out != null ) return out; return in; } @Override - public void parseRecipes(IRecipeLoader loader, String path) + public void parseRecipes( IRecipeLoader loader, String path ) { try { @@ -372,10 +224,10 @@ public class RecipeHandler implements IRecipeHandler { reader = loader.getFile( path ); } - catch (Exception err) + catch( Exception err ) { AELog.warning( "Error Loading Recipe File:" + path ); - if ( this.data.exceptions ) + if( this.data.exceptions ) AELog.error( err ); return; } @@ -387,134 +239,281 @@ public class RecipeHandler implements IRecipeHandler int line = 0; int val = -1; - while ((val = reader.read()) != -1) + while( ( val = reader.read() ) != -1 ) { char c = (char) val; - if ( c == '\n' ) + if( c == '\n' ) line++; - if ( inComment ) + if( inComment ) { - if ( c == '\n' || c == '\r' ) + if( c == '\n' || c == '\r' ) inComment = false; } - else if ( inQuote ) + else if( inQuote ) { - switch (c) + switch( c ) { - case '"': - inQuote = !inQuote; - break; - default: - token += c; + case '"': + inQuote = !inQuote; + break; + default: + token += c; } } else { - switch (c) + switch( c ) { - case '"': - inQuote = !inQuote; - break; - case ',': + case '"': + inQuote = !inQuote; + break; + case ',': - if ( token.length() > 0 ) - { - this.tokens.add( token ); - this.tokens.add( "," ); - } - token = ""; - break; + if( token.length() > 0 ) + { + this.tokens.add( token ); + this.tokens.add( "," ); + } + token = ""; + break; - case '=': + case '=': - this.processTokens( loader, path, line ); + this.processTokens( loader, path, line ); - if ( token.length() > 0 ) - this.tokens.add( token ); - token = ""; + if( token.length() > 0 ) + this.tokens.add( token ); + token = ""; - break; + break; - case '#': - inComment = true; - // then add a token if you can... + case '#': + inComment = true; + // then add a token if you can... - case '\n': - case '\t': - case '\r': - case ' ': + case '\n': + case '\t': + case '\r': + case ' ': - if ( token.length() > 0 ) - this.tokens.add( token ); - token = ""; + if( token.length() > 0 ) + this.tokens.add( token ); + token = ""; - break; - default: - token += c; + break; + default: + token += c; } } - } - if ( token.length() > 0 ) + if( token.length() > 0 ) this.tokens.add( token ); reader.close(); this.processTokens( loader, path, line ); } - catch (Throwable e) + catch( Throwable e ) { AELog.error( e ); - if ( this.data.crash ) + if( this.data.crash ) throw new RuntimeException( e ); } } - private void processTokens(IRecipeLoader loader, String file, int line) throws RecipeError + @Override + public void injectRecipes() + { + if( cpw.mods.fml.common.Loader.instance().hasReachedState( LoaderState.POSTINITIALIZATION ) ) + throw new RuntimeException( "Recipes must now be loaded in Init." ); + + HashMap processed = new HashMap(); + try + { + for( ICraftHandler ch : this.data.Handlers ) + { + try + { + ch.register(); + + Class clz = ch.getClass(); + Integer i = processed.get( clz ); + if( i == null ) + processed.put( clz, 1 ); + else + processed.put( clz, i + 1 ); + } + catch( RegistrationError e ) + { + AELog.warning( "Unable to register a recipe: " + e.getMessage() ); + if( this.data.exceptions ) + AELog.error( e ); + if( this.data.crash ) + throw e; + } + catch( MissingIngredientError e ) + { + if( this.data.errorOnMissing ) + { + AELog.warning( "Unable to register a recipe:" + e.getMessage() ); + if( this.data.exceptions ) + AELog.error( e ); + if( this.data.crash ) + throw e; + } + } + } + } + catch( Throwable e ) + { + if( this.data.exceptions ) + AELog.error( e ); + if( this.data.crash ) + throw new RuntimeException( e ); + } + + for( Entry e : processed.entrySet() ) + { + AELog.info( "Recipes Loading: " + e.getKey().getSimpleName() + ": " + e.getValue() + " loaded." ); + } + + if( AEConfig.instance.isFeatureEnabled( AEFeature.WebsiteRecipes ) ) + { + try + { + ZipOutputStream out = new ZipOutputStream( new FileOutputStream( "recipes.zip" ) ); + + HashMultimap combined = HashMultimap.create(); + + for( String s : this.data.knownItem ) + { + try + { + + Ingredient i = new Ingredient( this, s, 1 ); + + for( ItemStack is : i.getItemStackSet() ) + { + String realName = this.getName( is ); + List recipes = this.findRecipe( is ); + if( !recipes.isEmpty() ) + combined.putAll( realName, recipes ); + } + } + catch( RecipeError ignored ) + { + + } + catch( MissedIngredientSet ignored ) + { + + } + catch( RegistrationError ignored ) + { + + } + catch( MissingIngredientError ignored ) + { + + } + } + + for( String realName : combined.keySet() ) + { + int offset = 0; + + for( IWebsiteSerializer ws : combined.get( realName ) ) + { + String rew = ws.getPattern( this ); + if( rew != null && rew.length() > 0 ) + { + out.putNextEntry( new ZipEntry( realName + '_' + offset + ".txt" ) ); + offset++; + out.write( rew.getBytes() ); + } + } + } + + out.close(); + } + catch( FileNotFoundException e1 ) + { + AELog.error( e1 ); + } + catch( IOException e1 ) + { + AELog.error( e1 ); + } + } + } + + public List findRecipe( ItemStack output ) + { + List out = new LinkedList(); + + for( ICraftHandler ch : this.data.Handlers ) + { + try + { + if( ch instanceof IWebsiteSerializer && ( (IWebsiteSerializer) ch ).canCraft( output ) ) + { + out.add( (IWebsiteSerializer) ch ); + } + } + catch( Throwable t ) + { + AELog.error( t ); + } + } + + return out; + } + + private void processTokens( IRecipeLoader loader, String file, int line ) throws RecipeError { try { IRecipeHandlerRegistry cr = AEApi.instance().registries().recipes(); - if ( this.tokens.isEmpty() ) + if( this.tokens.isEmpty() ) return; int split = this.tokens.indexOf( "->" ); - if ( split != -1 ) + if( split != -1 ) { String operation = this.tokens.remove( 0 ).toLowerCase(); - if ( operation.equals( "alias" ) ) + if( operation.equals( "alias" ) ) { - if ( this.tokens.size() == 3 && this.tokens.indexOf( "->" ) == 1 ) + if( this.tokens.size() == 3 && this.tokens.indexOf( "->" ) == 1 ) this.data.aliases.put( this.tokens.get( 0 ), this.tokens.get( 2 ) ); else throw new RecipeError( "Alias must have exactly 1 input and 1 output." ); } - else if ( operation.equals( "group" ) ) + else if( operation.equals( "group" ) ) { List pre = this.tokens.subList( 0, split - 1 ); List post = this.tokens.subList( split, this.tokens.size() ); List> inputs = this.parseLines( pre ); - if ( inputs.size() == 1 && inputs.get( 0 ).size() > 0 && post.size() == 1 ) + if( inputs.size() == 1 && inputs.get( 0 ).size() > 0 && post.size() == 1 ) { this.data.groups.put( post.get( 0 ), new GroupIngredient( post.get( 0 ), inputs.get( 0 ) ) ); } else throw new RecipeError( "Group must have exactly 1 output, and 1 or more inputs." ); } - else if ( operation.equals( "ore" ) ) + else if( operation.equals( "ore" ) ) { List pre = this.tokens.subList( 0, split - 1 ); List post = this.tokens.subList( split, this.tokens.size() ); List> inputs = this.parseLines( pre ); - if ( inputs.size() == 1 && inputs.get( 0 ).size() > 0 && post.size() == 1 ) + if( inputs.size() == 1 && inputs.get( 0 ).size() > 0 && post.size() == 1 ) { ICraftHandler ch = new OreRegistration( inputs.get( 0 ), post.get( 0 ) ); this.addCrafting( ch ); @@ -532,7 +531,7 @@ public class RecipeHandler implements IRecipeHandler ICraftHandler ch = cr.getCraftHandlerFor( operation ); - if ( ch != null ) + if( ch != null ) { ch.setup( inputs, outputs ); this.addCrafting( ch ); @@ -545,58 +544,57 @@ public class RecipeHandler implements IRecipeHandler { String operation = this.tokens.remove( 0 ).toLowerCase(); - if ( operation.equals( "exceptions" ) && (this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" )) ) + if( operation.equals( "exceptions" ) && ( this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" ) ) ) { - if ( this.tokens.size() == 1 ) + if( this.tokens.size() == 1 ) { this.data.exceptions = this.tokens.get( 0 ).equals( "true" ); } else throw new RecipeError( "exceptions must be true or false explicitly." ); } - else if ( operation.equals( "crash" ) && (this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" )) ) + else if( operation.equals( "crash" ) && ( this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" ) ) ) { - if ( this.tokens.size() == 1 ) + if( this.tokens.size() == 1 ) { this.data.crash = this.tokens.get( 0 ).equals( "true" ); } else throw new RecipeError( "crash must be true or false explicitly." ); } - else if ( operation.equals( "erroronmissing" ) ) + else if( operation.equals( "erroronmissing" ) ) { - if ( this.tokens.size() == 1 && (this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" )) ) + if( this.tokens.size() == 1 && ( this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" ) ) ) { this.data.errorOnMissing = this.tokens.get( 0 ).equals( "true" ); } else throw new RecipeError( "erroronmissing must be true or false explicitly." ); } - else if ( operation.equals( "import" ) ) + else if( operation.equals( "import" ) ) { - if ( this.tokens.size() == 1 ) - (new RecipeHandler( this )).parseRecipes( loader, this.tokens.get( 0 ) ); + if( this.tokens.size() == 1 ) + ( new RecipeHandler( this ) ).parseRecipes( loader, this.tokens.get( 0 ) ); else throw new RecipeError( "Import must have exactly 1 input." ); } else throw new RecipeError( operation + ": " + this.tokens.toString() + "; recipe without an output." ); } - } - catch (RecipeError e) + catch( RecipeError e ) { AELog.warning( "Recipe Error '" + e.getMessage() + "' near line:" + line + " in " + file + " with: " + this.tokens.toString() ); - if ( this.data.exceptions ) + if( this.data.exceptions ) AELog.error( e ); - if ( this.data.crash ) + if( this.data.crash ) throw e; } this.tokens.clear(); } - private List> parseLines(List subList) throws RecipeError + private List> parseLines( List subList ) throws RecipeError { List> out = new LinkedList>(); List cList = new LinkedList(); @@ -604,28 +602,28 @@ public class RecipeHandler implements IRecipeHandler boolean hasQty = false; int qty = 1; - for (String v : subList) + for( String v : subList ) { - if ( v.equals( "," ) ) + if( v.equals( "," ) ) { - if ( hasQty ) + if( hasQty ) throw new RecipeError( "Qty found with no item." ); - if ( !cList.isEmpty() ) + if( !cList.isEmpty() ) out.add( cList ); cList = new LinkedList(); } else { - if ( this.isNumber( v ) ) + if( this.isNumber( v ) ) { - if ( hasQty ) + if( hasQty ) throw new RecipeError( "Qty found with no item." ); hasQty = true; qty = Integer.parseInt( v ); } else { - if ( hasQty ) + if( hasQty ) { cList.add( this.findIngredient( v, qty ) ); hasQty = false; @@ -636,42 +634,41 @@ public class RecipeHandler implements IRecipeHandler } } - if ( !cList.isEmpty() ) + if( !cList.isEmpty() ) out.add( cList ); return out; } - private IIngredient findIngredient(String v, int qty) throws RecipeError + private IIngredient findIngredient( String v, int qty ) throws RecipeError { GroupIngredient gi = this.data.groups.get( v ); - if ( gi != null ) + if( gi != null ) return gi.copy( qty ); try { return new Ingredient( this, v, qty ); } - catch (MissedIngredientSet grp) + catch( MissedIngredientSet grp ) { return new IngredientSet( grp.rrs ); } } - private boolean isNumber(String v) + private boolean isNumber( String v ) { - if ( v.length() <= 0 ) + if( v.length() <= 0 ) return false; int l = v.length(); - for (int x = 0; x < l; x++) + for( int x = 0; x < l; x++ ) { - if ( !Character.isDigit( v.charAt( x ) ) ) + if( !Character.isDigit( v.charAt( x ) ) ) return false; } return true; } - } diff --git a/src/main/java/appeng/recipes/game/DisassembleRecipe.java b/src/main/java/appeng/recipes/game/DisassembleRecipe.java index 7a524d511..484d58423 100644 --- a/src/main/java/appeng/recipes/game/DisassembleRecipe.java +++ b/src/main/java/appeng/recipes/game/DisassembleRecipe.java @@ -80,31 +80,31 @@ public class DisassembleRecipe implements IRecipe { ItemStack hasCell = null; - for ( int x = 0; x < inv.getSizeInventory(); x++ ) + for( int x = 0; x < inv.getSizeInventory(); x++ ) { ItemStack is = inv.getStackInSlot( x ); - if ( is != null ) + if( is != null ) { - if ( hasCell != null ) + if( hasCell != null ) return null; hasCell = this.getCellOutput( is ); // make sure the storage cell is empty... - if ( hasCell != null ) + if( hasCell != null ) { IMEInventory cellInv = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - if ( cellInv != null ) + if( cellInv != null ) { IItemList list = cellInv.getAvailableItems( StorageChannel.ITEMS.createList() ); - if ( !list.isEmpty() ) + if( !list.isEmpty() ) return null; } } hasCell = this.getNonCellOutput( is ); - if ( hasCell == null ) + if( hasCell == null ) return null; } } @@ -114,9 +114,9 @@ public class DisassembleRecipe implements IRecipe private ItemStack getCellOutput( ItemStack compared ) { - for ( Map.Entry entry : this.cellMappings.entrySet() ) + for( Map.Entry entry : this.cellMappings.entrySet() ) { - if ( entry.getKey().isSameAs( compared ) ) + if( entry.getKey().isSameAs( compared ) ) { return entry.getValue().maybeStack( 1 ).get(); } @@ -127,9 +127,9 @@ public class DisassembleRecipe implements IRecipe private ItemStack getNonCellOutput( ItemStack compared ) { - for ( Map.Entry entry : this.nonCellMappings.entrySet() ) + for( Map.Entry entry : this.nonCellMappings.entrySet() ) { - if ( entry.getKey().isSameAs( compared ) ) + if( entry.getKey().isSameAs( compared ) ) { return entry.getValue().maybeStack( 1 ).get(); } diff --git a/src/main/java/appeng/recipes/game/FacadeRecipe.java b/src/main/java/appeng/recipes/game/FacadeRecipe.java index 4ef65a260..4b721554d 100644 --- a/src/main/java/appeng/recipes/game/FacadeRecipe.java +++ b/src/main/java/appeng/recipes/game/FacadeRecipe.java @@ -59,16 +59,16 @@ public final class FacadeRecipe implements IRecipe @Nullable private ItemStack getOutput( IInventory inv, boolean createFacade ) { - if ( inv.getStackInSlot( 0 ) == null && inv.getStackInSlot( 2 ) == null && inv.getStackInSlot( 6 ) == null && inv.getStackInSlot( 8 ) == null ) + if( inv.getStackInSlot( 0 ) == null && inv.getStackInSlot( 2 ) == null && inv.getStackInSlot( 6 ) == null && inv.getStackInSlot( 8 ) == null ) { - if ( this.anchor.isSameAs( inv.getStackInSlot( 1 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 3 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 5 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 7 ) ) ) + if( this.anchor.isSameAs( inv.getStackInSlot( 1 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 3 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 5 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 7 ) ) ) { - for ( Item facadeItemDefinition : this.maybeFacade.asSet() ) + for( Item facadeItemDefinition : this.maybeFacade.asSet() ) { final ItemFacade facade = (ItemFacade) facadeItemDefinition; ItemStack facades = facade.createFacadeForItem( inv.getStackInSlot( 4 ), !createFacade ); - if ( facades != null && createFacade ) + if( facades != null && createFacade ) facades.stackSize = 4; return facades; } diff --git a/src/main/java/appeng/recipes/game/ShapedRecipe.java b/src/main/java/appeng/recipes/game/ShapedRecipe.java index fe6c2a1eb..b9d3387fc 100644 --- a/src/main/java/appeng/recipes/game/ShapedRecipe.java +++ b/src/main/java/appeng/recipes/game/ShapedRecipe.java @@ -18,6 +18,7 @@ package appeng.recipes.game; + import java.util.ArrayList; import java.util.HashMap; @@ -31,6 +32,7 @@ import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; + public class ShapedRecipe implements IRecipe, IRecipeBakeable { @@ -45,22 +47,17 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable private boolean mirrored = true; private boolean disable = false; - public boolean isEnabled() - { - return !this.disable; - } - - public ShapedRecipe(ItemStack result, Object... recipe) + public ShapedRecipe( ItemStack result, Object... recipe ) { this.output = result.copy(); StringBuilder shape = new StringBuilder(); int idx = 0; - if ( recipe[idx] instanceof Boolean ) + if( recipe[idx] instanceof Boolean ) { this.mirrored = (Boolean) recipe[idx]; - if ( recipe[idx + 1] instanceof Object[] ) + if( recipe[idx + 1] instanceof Object[] ) { recipe = (Object[]) recipe[idx + 1]; } @@ -70,12 +67,12 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable } } - if ( recipe[idx] instanceof String[] ) + if( recipe[idx] instanceof String[] ) { - String[] parts = ((String[]) recipe[idx]); + String[] parts = ( (String[]) recipe[idx] ); idx++; - for (String s : parts) + for( String s : parts ) { this.width = s.length(); shape.append( s ); @@ -85,7 +82,7 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable } else { - while (recipe[idx] instanceof String) + while( recipe[idx] instanceof String ) { String s = (String) recipe[idx]; idx++; @@ -95,10 +92,10 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable } } - if ( this.width * this.height != shape.length() ) + if( this.width * this.height != shape.length() ) { StringBuilder ret = new StringBuilder( "Invalid shaped ore recipe: " ); - for (Object tmp : recipe) + for( Object tmp : recipe ) { ret.append( tmp ).append( ", " ); } @@ -108,19 +105,19 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable HashMap itemMap = new HashMap(); - for (; idx < recipe.length; idx += 2) + for(; idx < recipe.length; idx += 2 ) { Character chr = (Character) recipe[idx]; Object in = recipe[idx + 1]; - if ( in instanceof IIngredient ) + if( in instanceof IIngredient ) { itemMap.put( chr, in ); } else { StringBuilder ret = new StringBuilder( "Invalid shaped ore recipe: " ); - for (Object tmp : recipe) + for( Object tmp : recipe ) { ret.append( tmp ).append( ", " ); } @@ -131,15 +128,45 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable this.input = new Object[this.width * this.height]; int x = 0; - for (char chr : shape.toString().toCharArray()) + for( char chr : shape.toString().toCharArray() ) { this.input[x] = itemMap.get( chr ); x++; } } + public boolean isEnabled() + { + return !this.disable; + } + @Override - public ItemStack getCraftingResult(InventoryCrafting var1) + public boolean matches( InventoryCrafting inv, World world ) + { + if( this.disable ) + return false; + + for( int x = 0; x <= MAX_CRAFT_GRID_WIDTH - this.width; x++ ) + { + for( int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - this.height; ++y ) + { + if( this.checkMatch( inv, x, y, false ) ) + { + return true; + } + + if( this.mirrored && this.checkMatch( inv, x, y, true ) ) + { + return true; + } + } + } + + return false; + } + + @Override + public ItemStack getCraftingResult( InventoryCrafting var1 ) { return this.output.copy(); } @@ -156,48 +183,23 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable return this.output; } - @Override - public boolean matches(InventoryCrafting inv, World world) + @SuppressWarnings( "unchecked" ) + private boolean checkMatch( InventoryCrafting inv, int startX, int startY, boolean mirror ) { - if ( this.disable ) + if( this.disable ) return false; - for (int x = 0; x <= MAX_CRAFT_GRID_WIDTH - this.width; x++) + for( int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++ ) { - for (int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - this.height; ++y) - { - if ( this.checkMatch( inv, x, y, false ) ) - { - return true; - } - - if ( this.mirrored && this.checkMatch( inv, x, y, true ) ) - { - return true; - } - } - } - - return false; - } - - @SuppressWarnings("unchecked") - private boolean checkMatch(InventoryCrafting inv, int startX, int startY, boolean mirror) - { - if ( this.disable ) - return false; - - for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) - { - for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) + for( int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++ ) { int subX = x - startX; int subY = y - startY; Object target = null; - if ( subX >= 0 && subY >= 0 && subX < this.width && subY < this.height ) + if( subX >= 0 && subY >= 0 && subX < this.width && subY < this.height ) { - if ( mirror ) + if( mirror ) { target = this.input[this.width - subX - 1 + subY * this.width]; } @@ -209,46 +211,46 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable ItemStack slot = inv.getStackInRowAndColumn( x, y ); - if ( target instanceof IIngredient ) + if( target instanceof IIngredient ) { boolean matched = false; try { - for (ItemStack item : ((IIngredient) target).getItemStackSet()) + for( ItemStack item : ( (IIngredient) target ).getItemStackSet() ) { matched = matched || this.checkItemEquals( item, slot ); } } - catch (RegistrationError e) + catch( RegistrationError e ) { // :P } - catch (MissingIngredientError e) + catch( MissingIngredientError e ) { // :P } - if ( !matched ) + if( !matched ) { return false; } } - else if ( target instanceof ArrayList ) + else if( target instanceof ArrayList ) { boolean matched = false; - for (ItemStack item : (ArrayList) target) + for( ItemStack item : (ArrayList) target ) { matched = matched || this.checkItemEquals( item, slot ); } - if ( !matched ) + if( !matched ) { return false; } } - else if ( target == null && slot != null ) + else if( target == null && slot != null ) { return false; } @@ -258,17 +260,16 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable return true; } - private boolean checkItemEquals(ItemStack target, ItemStack input) + private boolean checkItemEquals( ItemStack target, ItemStack input ) { - if ( input == null && target != null || input != null && target == null ) + if( input == null && target != null || input != null && target == null ) { return false; } - return (target.getItem() == input.getItem() && (target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input - .getItemDamage())); + return ( target.getItem() == input.getItem() && ( target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input.getItemDamage() ) ); } - public ShapedRecipe setMirrored(boolean mirror) + public ShapedRecipe setMirrored( boolean mirror ) { this.mirrored = mirror; return this; @@ -306,16 +307,15 @@ public class ShapedRecipe implements IRecipe, IRecipeBakeable try { this.disable = false; - for (Object o : this.input ) + for( Object o : this.input ) { - if ( o instanceof IIngredient ) - ((IIngredient) o).bake(); + if( o instanceof IIngredient ) + ( (IIngredient) o ).bake(); } } - catch (MissingIngredientError err) + catch( MissingIngredientError err ) { this.disable = true; } } - } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/game/ShapelessRecipe.java b/src/main/java/appeng/recipes/game/ShapelessRecipe.java index 2c87dade5..3ff832e0b 100644 --- a/src/main/java/appeng/recipes/game/ShapelessRecipe.java +++ b/src/main/java/appeng/recipes/game/ShapelessRecipe.java @@ -18,6 +18,7 @@ package appeng.recipes.game; + import java.util.ArrayList; import net.minecraft.inventory.InventoryCrafting; @@ -30,31 +31,27 @@ import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; + public class ShapelessRecipe implements IRecipe, IRecipeBakeable { - private ItemStack output = null; private final ArrayList input = new ArrayList(); + private ItemStack output = null; private boolean disable = false; - public boolean isEnabled() - { - return !this.disable; - } - - public ShapelessRecipe(ItemStack result, Object... recipe) + public ShapelessRecipe( ItemStack result, Object... recipe ) { this.output = result.copy(); - for (Object in : recipe) + for( Object in : recipe ) { - if ( in instanceof IIngredient ) + if( in instanceof IIngredient ) { this.input.add( in ); } else { StringBuilder ret = new StringBuilder( "Invalid shapeless ore recipe: " ); - for (Object tmp : recipe) + for( Object tmp : recipe ) { ret.append( tmp ).append( ", " ); } @@ -64,6 +61,75 @@ public class ShapelessRecipe implements IRecipe, IRecipeBakeable } } + public boolean isEnabled() + { + return !this.disable; + } + + @SuppressWarnings( "unchecked" ) + @Override + public boolean matches( InventoryCrafting var1, World world ) + { + if( this.disable ) + return false; + + ArrayList required = new ArrayList( this.input ); + + for( int x = 0; x < var1.getSizeInventory(); x++ ) + { + ItemStack slot = var1.getStackInSlot( x ); + + if( slot != null ) + { + boolean inRecipe = false; + + for( Object next : required ) + { + boolean match = false; + + if( next instanceof IIngredient ) + { + try + { + for( ItemStack item : ( (IIngredient) next ).getItemStackSet() ) + { + match = match || this.checkItemEquals( item, slot ); + } + } + catch( RegistrationError e ) + { + // :P + } + catch( MissingIngredientError e ) + { + // :P + } + } + + if( match ) + { + inRecipe = true; + required.remove( next ); + break; + } + } + + if( !inRecipe ) + { + return false; + } + } + } + + return required.isEmpty(); + } + + @Override + public ItemStack getCraftingResult( InventoryCrafting var1 ) + { + return this.output.copy(); + } + @Override public int getRecipeSize() { @@ -76,74 +142,9 @@ public class ShapelessRecipe implements IRecipe, IRecipeBakeable return this.output; } - @Override - public ItemStack getCraftingResult(InventoryCrafting var1) + private boolean checkItemEquals( ItemStack target, ItemStack input ) { - return this.output.copy(); - } - - @SuppressWarnings("unchecked") - @Override - public boolean matches(InventoryCrafting var1, World world) - { - if ( this.disable ) - return false; - - ArrayList required = new ArrayList( this.input ); - - for (int x = 0; x < var1.getSizeInventory(); x++) - { - ItemStack slot = var1.getStackInSlot( x ); - - if ( slot != null ) - { - boolean inRecipe = false; - - for (Object next : required) - { - boolean match = false; - - if ( next instanceof IIngredient ) - { - try - { - for (ItemStack item : ((IIngredient) next).getItemStackSet()) - { - match = match || this.checkItemEquals( item, slot ); - } - } - catch (RegistrationError e) - { - // :P - } - catch (MissingIngredientError e) - { - // :P - } - } - - if ( match ) - { - inRecipe = true; - required.remove( next ); - break; - } - } - - if ( !inRecipe ) - { - return false; - } - } - } - - return required.isEmpty(); - } - - private boolean checkItemEquals(ItemStack target, ItemStack input) - { - return (target.getItem() == input.getItem() && (target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input - .getItemDamage())); + return ( target.getItem() == input.getItem() && ( target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input.getItemDamage() ) ); } /** @@ -163,13 +164,13 @@ public class ShapelessRecipe implements IRecipe, IRecipeBakeable try { this.disable = false; - for (Object o : this.input ) + for( Object o : this.input ) { - if ( o instanceof IIngredient ) - ((IIngredient) o).bake(); + if( o instanceof IIngredient ) + ( (IIngredient) o ).bake(); } } - catch (MissingIngredientError e) + catch( MissingIngredientError e ) { this.disable = true; } diff --git a/src/main/java/appeng/recipes/handlers/Crusher.java b/src/main/java/appeng/recipes/handlers/Crusher.java index e1aea8ef1..2529b2c03 100644 --- a/src/main/java/appeng/recipes/handlers/Crusher.java +++ b/src/main/java/appeng/recipes/handlers/Crusher.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; + import java.util.List; import net.minecraft.item.ItemStack; @@ -34,6 +35,7 @@ import appeng.integration.abstraction.IRC; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class Crusher implements ICraftHandler, IWebsiteSerializer { @@ -41,12 +43,12 @@ public class Crusher implements ICraftHandler, IWebsiteSerializer IIngredient[] pro_output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { int outs = output.get( 0 ).size(); - if ( input.get( 0 ).size() == 1 && outs == 1 ) + if( input.get( 0 ).size() == 1 && outs == 1 ) { this.pro_input = input.get( 0 ).get( 0 ); this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); @@ -59,16 +61,16 @@ public class Crusher implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.RC ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.RC ) ) { IRC rc = (IRC) AppEng.instance.getIntegration( IntegrationType.RC ); - for (ItemStack is : this.pro_input.getItemStackSet()) + for( ItemStack is : this.pro_input.getItemStackSet() ) { try { rc.rockCrusher( is, this.pro_output[0].getItemStack() ); } - catch (java.lang.RuntimeException err) + catch( java.lang.RuntimeException err ) { AELog.info( "RC not happy - " + err.getMessage() ); } @@ -77,15 +79,14 @@ public class Crusher implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { return null; } + @Override + public boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); + } } diff --git a/src/main/java/appeng/recipes/handlers/Grind.java b/src/main/java/appeng/recipes/handlers/Grind.java index 41d801ec5..308530bc9 100644 --- a/src/main/java/appeng/recipes/handlers/Grind.java +++ b/src/main/java/appeng/recipes/handlers/Grind.java @@ -32,6 +32,7 @@ import appeng.api.recipes.IIngredient; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class Grind implements ICraftHandler, IWebsiteSerializer { @@ -39,12 +40,12 @@ public class Grind implements ICraftHandler, IWebsiteSerializer IIngredient[] pro_output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { int outs = output.get( 0 ).size(); - if ( input.get( 0 ).size() == 1 && outs == 1 ) + if( input.get( 0 ).size() == 1 && outs == 1 ) { this.pro_input = input.get( 0 ).get( 0 ); this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); @@ -57,20 +58,21 @@ public class Grind implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - for (ItemStack is : this.pro_input.getItemStackSet()) + for( ItemStack is : this.pro_input.getItemStackSet() ) AEApi.instance().registries().grinder().addRecipe( is, this.pro_output[0].getItemStack(), 8 ); } @Override - public boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(),output ); + public String getPattern( RecipeHandler h ) + { + return "grind\n" + + h.getName( this.pro_input ) + '\n' + + h.getName( this.pro_output[0] ); } @Override - public String getPattern( RecipeHandler h ) { - return "grind\n"+ - h.getName(this.pro_input)+ '\n' + - h.getName(this.pro_output[0]); + public boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); } - } diff --git a/src/main/java/appeng/recipes/handlers/GrindFZ.java b/src/main/java/appeng/recipes/handlers/GrindFZ.java index 96adf598f..9e41b5cf8 100644 --- a/src/main/java/appeng/recipes/handlers/GrindFZ.java +++ b/src/main/java/appeng/recipes/handlers/GrindFZ.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; + import java.util.List; import net.minecraft.item.ItemStack; @@ -34,6 +35,7 @@ import appeng.integration.abstraction.IFZ; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class GrindFZ implements ICraftHandler, IWebsiteSerializer { @@ -41,12 +43,12 @@ public class GrindFZ implements ICraftHandler, IWebsiteSerializer IIngredient[] pro_output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { int outs = output.get( 0 ).size(); - if ( input.get( 0 ).size() == 1 && outs == 1 ) + if( input.get( 0 ).size() == 1 && outs == 1 ) { this.pro_input = input.get( 0 ).get( 0 ); this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); @@ -59,16 +61,16 @@ public class GrindFZ implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.FZ ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.FZ ) ) { IFZ fz = (IFZ) AppEng.instance.getIntegration( IntegrationType.FZ ); - for (ItemStack is : this.pro_input.getItemStackSet()) + for( ItemStack is : this.pro_input.getItemStackSet() ) { try { fz.grinderRecipe( is, this.pro_output[0].getItemStack() ); } - catch (java.lang.RuntimeException err) + catch( java.lang.RuntimeException err ) { AELog.info( "FZ not happy - " + err.getMessage() ); } @@ -77,15 +79,14 @@ public class GrindFZ implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { return null; } + @Override + public boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); + } } diff --git a/src/main/java/appeng/recipes/handlers/HCCrusher.java b/src/main/java/appeng/recipes/handlers/HCCrusher.java index 94b507005..763d81eaf 100644 --- a/src/main/java/appeng/recipes/handlers/HCCrusher.java +++ b/src/main/java/appeng/recipes/handlers/HCCrusher.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; + import java.util.List; import net.minecraft.item.ItemStack; @@ -34,6 +35,7 @@ import appeng.core.AELog; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class HCCrusher implements ICraftHandler, IWebsiteSerializer { @@ -41,12 +43,12 @@ public class HCCrusher implements ICraftHandler, IWebsiteSerializer IIngredient[] pro_output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { int outs = output.get( 0 ).size(); - if ( input.get( 0 ).size() == 1 && outs == 1 ) + if( input.get( 0 ).size() == 1 && outs == 1 ) { this.pro_input = input.get( 0 ).get( 0 ); this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); @@ -59,7 +61,7 @@ public class HCCrusher implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - for (ItemStack beginStack : this.pro_input.getItemStackSet()) + for( ItemStack beginStack : this.pro_input.getItemStackSet() ) { try { @@ -71,15 +73,15 @@ public class HCCrusher implements ICraftHandler, IWebsiteSerializer NBTTagCompound itemTo = new NBTTagCompound(); beginStack.writeToNBT( itemFrom ); - endStack.writeToNBT(itemTo); + endStack.writeToNBT( itemTo ); - toRegister.setTag("itemFrom", itemFrom); - toRegister.setTag("itemTo", itemTo); - toRegister.setFloat("pressureRatio", 1.0F); + toRegister.setTag( "itemFrom", itemFrom ); + toRegister.setTag( "itemTo", itemTo ); + toRegister.setFloat( "pressureRatio", 1.0F ); - FMLInterModComms.sendMessage("HydCraft", "registerCrushingRecipe", toRegister); + FMLInterModComms.sendMessage( "HydCraft", "registerCrushingRecipe", toRegister ); } - catch (java.lang.RuntimeException err) + catch( java.lang.RuntimeException err ) { AELog.info( "Hydraulicraft not happy - " + err.getMessage() ); } @@ -87,15 +89,14 @@ public class HCCrusher implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { return null; } + @Override + public boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); + } } diff --git a/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java b/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java index ba65ebb00..f15d77323 100644 --- a/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java +++ b/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java @@ -18,17 +18,18 @@ package appeng.recipes.handlers; + import net.minecraft.item.ItemStack; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.recipes.RecipeHandler; + public interface IWebsiteSerializer { - String getPattern(RecipeHandler han); - - boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError; + String getPattern( RecipeHandler han ); + boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError; } diff --git a/src/main/java/appeng/recipes/handlers/Inscribe.java b/src/main/java/appeng/recipes/handlers/Inscribe.java index f0785fbae..83af0f88c 100644 --- a/src/main/java/appeng/recipes/handlers/Inscribe.java +++ b/src/main/java/appeng/recipes/handlers/Inscribe.java @@ -34,54 +34,31 @@ import appeng.api.recipes.IIngredient; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class Inscribe implements ICraftHandler, IWebsiteSerializer { - public static class InscriberRecipe - { - - public InscriberRecipe(ItemStack[] imprintable, ItemStack plateA, ItemStack plateB, ItemStack out, boolean usePlates) { - this.imprintable = imprintable; - this.usePlates = usePlates; - this.plateA = plateA; - this.plateB = plateB; - this.output = out; - } - - final public boolean usePlates; - - final public ItemStack plateA; - final public ItemStack[] imprintable; - final public ItemStack plateB; - final public ItemStack output; - - } - - public boolean usePlates = false; - public static final HashSet PLATES = new HashSet(); public static final HashSet INPUTS = new HashSet(); public static final LinkedList RECIPES = new LinkedList(); - + public boolean usePlates = false; IIngredient imprintable; - IIngredient plateA; IIngredient plateB; - IIngredient output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( output.size() == 1 && output.get( 0 ).size() == 1 ) + if( output.size() == 1 && output.get( 0 ).size() == 1 ) { - if ( input.size() == 1 && input.get( 0 ).size() > 1 ) + if( input.size() == 1 && input.get( 0 ).size() > 1 ) { this.imprintable = input.get( 0 ).get( 0 ); this.plateA = input.get( 0 ).get( 1 ); - if ( input.get( 0 ).size() > 2 ) + if( input.get( 0 ).size() > 2 ) this.plateB = input.get( 0 ).get( 2 ); this.output = output.get( 0 ).get( 0 ); @@ -96,42 +73,59 @@ public class Inscribe implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - if ( this.imprintable != null ) + if( this.imprintable != null ) Collections.addAll( INPUTS, this.imprintable.getItemStackSet() ); - if ( this.plateA != null ) + if( this.plateA != null ) Collections.addAll( PLATES, this.plateA.getItemStackSet() ); - if ( this.plateB != null ) + if( this.plateB != null ) Collections.addAll( PLATES, this.plateB.getItemStackSet() ); - InscriberRecipe ir = new InscriberRecipe( this.imprintable.getItemStackSet(), this.plateA == null ? null : this.plateA.getItemStack(), this.plateB == null ? null - : this.plateB.getItemStack(), this.output.getItemStack(), this.usePlates ); + InscriberRecipe ir = new InscriberRecipe( this.imprintable.getItemStackSet(), this.plateA == null ? null : this.plateA.getItemStack(), this.plateB == null ? null : this.plateB.getItemStack(), this.output.getItemStack(), this.usePlates ); RECIPES.add( ir ); } @Override - public boolean canCraft(ItemStack reqOutput) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { String o = "inscriber " + this.output.getQty() + '\n'; o += h.getName( this.output ) + '\n'; - if ( this.plateA != null ) - o += h.getName( this.plateA )+ '\n'; + if( this.plateA != null ) + o += h.getName( this.plateA ) + '\n'; - o += h.getName(this.imprintable); + o += h.getName( this.imprintable ); - if ( this.plateB != null ) - o += '\n' +h.getName( this.plateB ); + if( this.plateB != null ) + o += '\n' + h.getName( this.plateB ); return o; } + @Override + public boolean canCraft( ItemStack reqOutput ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); + } + + public static class InscriberRecipe + { + + final public boolean usePlates; + final public ItemStack plateA; + final public ItemStack[] imprintable; + final public ItemStack plateB; + final public ItemStack output; + + public InscriberRecipe( ItemStack[] imprintable, ItemStack plateA, ItemStack plateB, ItemStack out, boolean usePlates ) + { + this.imprintable = imprintable; + this.usePlates = usePlates; + this.plateA = plateA; + this.plateB = plateB; + this.output = out; + } + } } diff --git a/src/main/java/appeng/recipes/handlers/Macerator.java b/src/main/java/appeng/recipes/handlers/Macerator.java index f45022c49..a19bf19c8 100644 --- a/src/main/java/appeng/recipes/handlers/Macerator.java +++ b/src/main/java/appeng/recipes/handlers/Macerator.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; + import java.util.List; import net.minecraft.item.ItemStack; @@ -34,6 +35,7 @@ import appeng.integration.abstraction.IIC2; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class Macerator implements ICraftHandler, IWebsiteSerializer { @@ -41,12 +43,12 @@ public class Macerator implements ICraftHandler, IWebsiteSerializer IIngredient[] pro_output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { int outs = output.get( 0 ).size(); - if ( input.get( 0 ).size() == 1 && outs == 1 ) + if( input.get( 0 ).size() == 1 && outs == 1 ) { this.pro_input = input.get( 0 ).get( 0 ); this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); @@ -59,16 +61,16 @@ public class Macerator implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.IC2 ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.IC2 ) ) { IIC2 ic2 = (IIC2) AppEng.instance.getIntegration( IntegrationType.IC2 ); - for (ItemStack is : this.pro_input.getItemStackSet()) + for( ItemStack is : this.pro_input.getItemStackSet() ) { try { ic2.maceratorRecipe( is, this.pro_output[0].getItemStack() ); } - catch (java.lang.RuntimeException err) + catch( java.lang.RuntimeException err ) { AELog.info( "IC2 not happy - " + err.getMessage() ); } @@ -77,15 +79,14 @@ public class Macerator implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { return null; } + @Override + public boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); + } } diff --git a/src/main/java/appeng/recipes/handlers/MekCrusher.java b/src/main/java/appeng/recipes/handlers/MekCrusher.java index 1864a66f0..f1b6ac479 100644 --- a/src/main/java/appeng/recipes/handlers/MekCrusher.java +++ b/src/main/java/appeng/recipes/handlers/MekCrusher.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; + import java.util.List; import net.minecraft.item.ItemStack; @@ -34,6 +35,7 @@ import appeng.integration.abstraction.IMekanism; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class MekCrusher implements ICraftHandler, IWebsiteSerializer { @@ -41,12 +43,12 @@ public class MekCrusher implements ICraftHandler, IWebsiteSerializer IIngredient[] pro_output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { int outs = output.get( 0 ).size(); - if ( input.get( 0 ).size() == 1 && outs == 1 ) + if( input.get( 0 ).size() == 1 && outs == 1 ) { this.pro_input = input.get( 0 ).get( 0 ); this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); @@ -59,16 +61,16 @@ public class MekCrusher implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.Mekanism ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.Mekanism ) ) { IMekanism rc = (IMekanism) AppEng.instance.getIntegration( IntegrationType.Mekanism ); - for (ItemStack is : this.pro_input.getItemStackSet()) + for( ItemStack is : this.pro_input.getItemStackSet() ) { try { rc.addCrusherRecipe( is, this.pro_output[0].getItemStack() ); } - catch (java.lang.RuntimeException err) + catch( java.lang.RuntimeException err ) { AELog.info( "Mekanism not happy - " + err.getMessage() ); } @@ -77,15 +79,14 @@ public class MekCrusher implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { return null; } + @Override + public boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); + } } diff --git a/src/main/java/appeng/recipes/handlers/MekEnrichment.java b/src/main/java/appeng/recipes/handlers/MekEnrichment.java index da28054b6..adbfbae48 100644 --- a/src/main/java/appeng/recipes/handlers/MekEnrichment.java +++ b/src/main/java/appeng/recipes/handlers/MekEnrichment.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; + import java.util.List; import net.minecraft.item.ItemStack; @@ -34,6 +35,7 @@ import appeng.integration.abstraction.IMekanism; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class MekEnrichment implements ICraftHandler, IWebsiteSerializer { @@ -41,12 +43,12 @@ public class MekEnrichment implements ICraftHandler, IWebsiteSerializer IIngredient[] pro_output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { int outs = output.get( 0 ).size(); - if ( input.get( 0 ).size() == 1 && outs == 1 ) + if( input.get( 0 ).size() == 1 && outs == 1 ) { this.pro_input = input.get( 0 ).get( 0 ); this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); @@ -59,16 +61,16 @@ public class MekEnrichment implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.Mekanism ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.Mekanism ) ) { IMekanism rc = (IMekanism) AppEng.instance.getIntegration( IntegrationType.Mekanism ); - for (ItemStack is : this.pro_input.getItemStackSet()) + for( ItemStack is : this.pro_input.getItemStackSet() ) { try { rc.addEnrichmentChamberRecipe( is, this.pro_output[0].getItemStack() ); } - catch (java.lang.RuntimeException err) + catch( java.lang.RuntimeException err ) { AELog.info( "Mekanism not happy - " + err.getMessage() ); } @@ -77,15 +79,14 @@ public class MekEnrichment implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { return null; } + @Override + public boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); + } } diff --git a/src/main/java/appeng/recipes/handlers/OreRegistration.java b/src/main/java/appeng/recipes/handlers/OreRegistration.java index 00ce5286e..f77738cb2 100644 --- a/src/main/java/appeng/recipes/handlers/OreRegistration.java +++ b/src/main/java/appeng/recipes/handlers/OreRegistration.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; + import java.util.List; import net.minecraft.item.ItemStack; @@ -29,33 +30,34 @@ import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.ICraftHandler; import appeng.api.recipes.IIngredient; + public class OreRegistration implements ICraftHandler { final List inputs; final String name; - public OreRegistration(List in, String out) { + public OreRegistration( List in, String out ) + { this.inputs = in; this.name = out; } + @Override + public void setup( List> input, List> output ) throws RecipeError + { + + } + @Override public void register() throws RegistrationError, MissingIngredientError { - for (IIngredient i : this.inputs) + for( IIngredient i : this.inputs ) { - for (ItemStack is : i.getItemStackSet()) + for( ItemStack is : i.getItemStackSet() ) { OreDictionary.registerOre( this.name, is ); } } } - - @Override - public void setup(List> input, List> output) throws RecipeError - { - - } - } diff --git a/src/main/java/appeng/recipes/handlers/Press.java b/src/main/java/appeng/recipes/handlers/Press.java index 66dc08cb5..9005ce076 100644 --- a/src/main/java/appeng/recipes/handlers/Press.java +++ b/src/main/java/appeng/recipes/handlers/Press.java @@ -18,11 +18,12 @@ package appeng.recipes.handlers; + public class Press extends Inscribe { - public Press() { + public Press() + { this.usePlates = true; } - } diff --git a/src/main/java/appeng/recipes/handlers/Pulverizer.java b/src/main/java/appeng/recipes/handlers/Pulverizer.java index d647e48e6..cd12fe353 100644 --- a/src/main/java/appeng/recipes/handlers/Pulverizer.java +++ b/src/main/java/appeng/recipes/handlers/Pulverizer.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; + import java.util.List; import net.minecraft.item.ItemStack; @@ -33,6 +34,7 @@ import appeng.api.recipes.IIngredient; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class Pulverizer implements ICraftHandler, IWebsiteSerializer { @@ -40,12 +42,12 @@ public class Pulverizer implements ICraftHandler, IWebsiteSerializer IIngredient[] pro_output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { int outs = output.get( 0 ).size(); - if ( input.get( 0 ).size() == 1 && outs == 1 ) + if( input.get( 0 ).size() == 1 && outs == 1 ) { this.pro_input = input.get( 0 ).get( 0 ); this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); @@ -64,7 +66,7 @@ public class Pulverizer implements ICraftHandler, IWebsiteSerializer this.pro_output[0].getItemStack().writeToNBT( toSend.getCompoundTag( "primaryOutput" ) ); - for (ItemStack is : this.pro_input.getItemStackSet()) + for( ItemStack is : this.pro_input.getItemStackSet() ) { toSend.setTag( "input", new NBTTagCompound() ); is.writeToNBT( toSend.getCompoundTag( "input" ) ); @@ -73,15 +75,14 @@ public class Pulverizer implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { return null; } + @Override + public boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); + } } diff --git a/src/main/java/appeng/recipes/handlers/Shaped.java b/src/main/java/appeng/recipes/handlers/Shaped.java index 0452fff9f..ea5db3d9b 100644 --- a/src/main/java/appeng/recipes/handlers/Shaped.java +++ b/src/main/java/appeng/recipes/handlers/Shaped.java @@ -36,29 +36,29 @@ import appeng.recipes.RecipeHandler; import appeng.recipes.game.ShapedRecipe; import appeng.util.Platform; + public class Shaped implements ICraftHandler, IWebsiteSerializer { + List> inputs; + IIngredient output; private int rows; private int cols; - List> inputs; - IIngredient output; - @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( output.size() == 1 && output.get( 0 ).size() == 1 ) + if( output.size() == 1 && output.get( 0 ).size() == 1 ) { this.rows = input.size(); - if ( this.rows > 0 && input.size() <= 3 ) + if( this.rows > 0 && input.size() <= 3 ) { this.cols = input.get( 0 ).size(); - if ( this.cols <= 3 && this.cols >= 1 ) + if( this.cols <= 3 && this.cols >= 1 ) { - for (List anInput : input) + for( List anInput : input ) { - if ( anInput.size() != this.cols ) + if( anInput.size() != this.cols ) { throw new RecipeError( "all rows in a shaped crafting recipe must contain the same number of ingredients." ); } @@ -83,12 +83,12 @@ public class Shaped implements ICraftHandler, IWebsiteSerializer char first = 'A'; List args = new ArrayList(); - for (int y = 0; y < this.rows; y++) + for( int y = 0; y < this.rows; y++ ) { StringBuilder row = new StringBuilder(); - for (int x = 0; x < this.cols; x++) + for( int x = 0; x < this.cols; x++ ) { - if ( this.inputs.get( y ).get( x ).isAir() ) + if( this.inputs.get( y ).get( x ).isAir() ) row.append( ' ' ); else { @@ -108,7 +108,7 @@ public class Shaped implements ICraftHandler, IWebsiteSerializer { GameRegistry.addRecipe( new ShapedRecipe( outIS, args.toArray( new Object[args.size()] ) ) ); } - catch (Throwable e) + catch( Throwable e ) { AELog.error( e ); throw new RegistrationError( "Error while adding shaped recipe." ); @@ -116,18 +116,39 @@ public class Shaped implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack reqOutput) throws RegistrationError, MissingIngredientError + public String getPattern( RecipeHandler h ) { - for (int y = 0; y < this.rows; y++) - for (int x = 0; x < this.cols; x++) + String o = "shaped " + this.output.getQty() + ' ' + this.cols + 'x' + this.rows + '\n'; + + o += h.getName( this.output ) + '\n'; + + for( int y = 0; y < this.rows; y++ ) + for( int x = 0; x < this.cols; x++ ) { IIngredient i = this.inputs.get( y ).get( x ); - if ( !i.isAir() ) + if( i.isAir() ) + o += "air" + ( x + 1 == this.cols ? "\n" : " " ); + else + o += h.getName( i ) + ( x + 1 == this.cols ? "\n" : " " ); + } + + return o.trim(); + } + + @Override + public boolean canCraft( ItemStack reqOutput ) throws RegistrationError, MissingIngredientError + { + for( int y = 0; y < this.rows; y++ ) + for( int x = 0; x < this.cols; x++ ) + { + IIngredient i = this.inputs.get( y ).get( x ); + + if( !i.isAir() ) { - for ( ItemStack r : i.getItemStackSet() ) + for( ItemStack r : i.getItemStackSet() ) { - if ( Platform.isSameItemPrecise( r, reqOutput) ) + if( Platform.isSameItemPrecise( r, reqOutput ) ) return false; } } @@ -135,25 +156,4 @@ public class Shaped implements ICraftHandler, IWebsiteSerializer return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); } - - @Override - public String getPattern(RecipeHandler h) - { - String o = "shaped " + this.output.getQty() + ' ' + this.cols + 'x' + this.rows + '\n'; - - o += h.getName( this.output ) + '\n'; - - for (int y = 0; y < this.rows; y++) - for (int x = 0; x < this.cols; x++) - { - IIngredient i = this.inputs.get( y ).get( x ); - - if ( i.isAir() ) - o += "air" + (x + 1 == this.cols ? "\n" : " "); - else - o += h.getName( i ) + (x + 1 == this.cols ? "\n" : " "); - } - - return o.trim(); - } } diff --git a/src/main/java/appeng/recipes/handlers/Shapeless.java b/src/main/java/appeng/recipes/handlers/Shapeless.java index cfcde935b..5ee59adae 100644 --- a/src/main/java/appeng/recipes/handlers/Shapeless.java +++ b/src/main/java/appeng/recipes/handlers/Shapeless.java @@ -36,6 +36,7 @@ import appeng.recipes.RecipeHandler; import appeng.recipes.game.ShapelessRecipe; import appeng.util.Platform; + public class Shapeless implements ICraftHandler, IWebsiteSerializer { @@ -43,11 +44,11 @@ public class Shapeless implements ICraftHandler, IWebsiteSerializer IIngredient output; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( output.size() == 1 && output.get( 0 ).size() == 1 ) + if( output.size() == 1 && output.get( 0 ).size() == 1 ) { - if ( input.size() == 1 ) + if( input.size() == 1 ) { this.inputs = input.get( 0 ); this.output = output.get( 0 ).get( 0 ); @@ -63,7 +64,7 @@ public class Shapeless implements ICraftHandler, IWebsiteSerializer public void register() throws RegistrationError, MissingIngredientError { List args = new ArrayList(); - for (IIngredient i : this.inputs) + for( IIngredient i : this.inputs ) args.add( i ); ItemStack outIS = this.output.getItemStack(); @@ -72,7 +73,7 @@ public class Shapeless implements ICraftHandler, IWebsiteSerializer { GameRegistry.addRecipe( new ShapelessRecipe( outIS, args.toArray( new Object[args.size()] ) ) ); } - catch (Throwable e) + catch( Throwable e ) { AELog.error( e ); throw new RegistrationError( "Error while adding shapeless recipe." ); @@ -80,38 +81,17 @@ public class Shapeless implements ICraftHandler, IWebsiteSerializer } @Override - public boolean canCraft(ItemStack reqOutput) throws RegistrationError, MissingIngredientError - { - - for (IIngredient i : this.inputs) - { - if ( !i.isAir() ) - { - for (ItemStack r : i.getItemStackSet()) - { - if ( Platform.isSameItemPrecise( r, reqOutput ) ) - { - return false; - } - } - } - } - - return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); - } - - @Override - public String getPattern(RecipeHandler h) + public String getPattern( RecipeHandler h ) { StringBuilder o = new StringBuilder( "shapeless " + this.output.getQty() + '\n' ); o.append( h.getName( this.output ) ).append( '\n' ); - for (int y = 0; y < this.inputs.size(); y++) + for( int y = 0; y < this.inputs.size(); y++ ) { IIngredient i = this.inputs.get( y ); - if ( i.isAir() ) + if( i.isAir() ) { o.append( "air" ); } @@ -120,7 +100,7 @@ public class Shapeless implements ICraftHandler, IWebsiteSerializer o.append( h.getName( i ) ); } - if ( y + 1 == this.inputs.size() ) + if( y + 1 == this.inputs.size() ) { o.append( '\n' ); } @@ -133,4 +113,24 @@ public class Shapeless implements ICraftHandler, IWebsiteSerializer return o.toString().trim(); } + @Override + public boolean canCraft( ItemStack reqOutput ) throws RegistrationError, MissingIngredientError + { + + for( IIngredient i : this.inputs ) + { + if( !i.isAir() ) + { + for( ItemStack r : i.getItemStackSet() ) + { + if( Platform.isSameItemPrecise( r, reqOutput ) ) + { + return false; + } + } + } + } + + return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); + } } diff --git a/src/main/java/appeng/recipes/handlers/Smelt.java b/src/main/java/appeng/recipes/handlers/Smelt.java index d3a45aaa1..ef6797674 100644 --- a/src/main/java/appeng/recipes/handlers/Smelt.java +++ b/src/main/java/appeng/recipes/handlers/Smelt.java @@ -33,6 +33,7 @@ import appeng.api.recipes.IIngredient; import appeng.recipes.RecipeHandler; import appeng.util.Platform; + public class Smelt implements ICraftHandler, IWebsiteSerializer { @@ -40,13 +41,13 @@ public class Smelt implements ICraftHandler, IWebsiteSerializer IIngredient out; @Override - public void setup(List> input, List> output) throws RecipeError + public void setup( List> input, List> output ) throws RecipeError { - if ( input.size() == 1 && output.size() == 1 ) + if( input.size() == 1 && output.size() == 1 ) { List inputList = input.get( 0 ); List outputList = output.get( 0 ); - if ( inputList.size() == 1 && outputList.size() == 1 ) + if( inputList.size() == 1 && outputList.size() == 1 ) { this.in = inputList.get( 0 ); this.out = outputList.get( 0 ); @@ -59,24 +60,26 @@ public class Smelt implements ICraftHandler, IWebsiteSerializer @Override public void register() throws RegistrationError, MissingIngredientError { - if ( this.in.getItemStack().getItem() == null ) + if( this.in.getItemStack().getItem() == null ) throw new RegistrationError( this.in.toString() + ": Smelting Input is not a valid item." ); - if ( this.out.getItemStack().getItem() == null ) + if( this.out.getItemStack().getItem() == null ) throw new RegistrationError( this.out.toString() + ": Smelting Output is not a valid item." ); GameRegistry.addSmelting( this.in.getItemStack(), this.out.getItemStack(), 0 ); } @Override - public boolean canCraft(ItemStack reqOutput) throws RegistrationError, MissingIngredientError { - return Platform.isSameItemPrecise( this.out.getItemStack(),reqOutput ); + public String getPattern( RecipeHandler h ) + { + return "smelt " + this.out.getQty() + '\n' + + h.getName( this.out ) + '\n' + + h.getName( this.in ); } @Override - public String getPattern( RecipeHandler h ) { - return "smelt "+this.out.getQty()+ '\n' + - h.getName(this.out)+ '\n' + - h.getName(this.in); + public boolean canCraft( ItemStack reqOutput ) throws RegistrationError, MissingIngredientError + { + return Platform.isSameItemPrecise( this.out.getItemStack(), reqOutput ); } } diff --git a/src/main/java/appeng/recipes/loader/JarLoader.java b/src/main/java/appeng/recipes/loader/JarLoader.java index 27f45a4ee..9a9bcafe1 100644 --- a/src/main/java/appeng/recipes/loader/JarLoader.java +++ b/src/main/java/appeng/recipes/loader/JarLoader.java @@ -18,24 +18,26 @@ package appeng.recipes.loader; + import java.io.BufferedReader; import java.io.InputStreamReader; import appeng.api.recipes.IRecipeLoader; + public class JarLoader implements IRecipeLoader { private final String rootPath; - public JarLoader(String s) { + public JarLoader( String s ) + { this.rootPath = s; } @Override - public BufferedReader getFile(String s) throws Exception + public BufferedReader getFile( String s ) throws Exception { return new BufferedReader( new InputStreamReader( this.getClass().getResourceAsStream( this.rootPath + s ), "UTF-8" ) ); } - } diff --git a/src/main/java/appeng/recipes/ores/IOreListener.java b/src/main/java/appeng/recipes/ores/IOreListener.java index b0e155cb8..404883719 100644 --- a/src/main/java/appeng/recipes/ores/IOreListener.java +++ b/src/main/java/appeng/recipes/ores/IOreListener.java @@ -18,8 +18,10 @@ package appeng.recipes.ores; + import net.minecraft.item.ItemStack; + public interface IOreListener { @@ -30,6 +32,5 @@ public interface IOreListener * @param name name of ore * @param item item with name */ - void oreRegistered(String name, ItemStack item); - + void oreRegistered( String name, ItemStack item ); } diff --git a/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java b/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java index 7743d5ba1..f47153544 100644 --- a/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java +++ b/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java @@ -18,6 +18,7 @@ package appeng.recipes.ores; + import java.util.ArrayList; import java.util.List; @@ -30,6 +31,7 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import appeng.core.AELog; import appeng.recipes.game.IRecipeBakeable; + public class OreDictionaryHandler { @@ -39,31 +41,52 @@ public class OreDictionaryHandler private boolean enableRebaking = false; + @SubscribeEvent + public void onOreDictionaryRegister( OreDictionary.OreRegisterEvent event ) + { + if( event.Name == null || event.Ore == null ) + return; + + if( this.shouldCare( event.Name ) ) + { + for( IOreListener v : this.ol ) + v.oreRegistered( event.Name, event.Ore ); + } + + if( this.enableRebaking ) + this.bakeRecipes(); + } + /** * Just limit what items are sent to the final listeners, I got sick of strange items showing up... * * @param name name about cared item + * * @return true if it should care */ - private boolean shouldCare(String name) + private boolean shouldCare( String name ) { return true; } - @SubscribeEvent - public void onOreDictionaryRegister(OreDictionary.OreRegisterEvent event) + public void bakeRecipes() { - if ( event.Name == null || event.Ore == null ) - return; + this.enableRebaking = true; - if ( this.shouldCare( event.Name ) ) + for( Object o : CraftingManager.getInstance().getRecipeList() ) { - for (IOreListener v : this.ol) - v.oreRegistered( event.Name, event.Ore ); + if( o instanceof IRecipeBakeable ) + { + try + { + ( (IRecipeBakeable) o ).bake(); + } + catch( Throwable e ) + { + AELog.error( e ); + } + } } - - if ( this.enableRebaking ) - this.bakeRecipes(); } /** @@ -72,42 +95,21 @@ public class OreDictionaryHandler * * @param n to be added ore listener */ - public void observe(IOreListener n) + public void observe( IOreListener n ) { this.ol.add( n ); // notify the listener of any ore already in existence. - for (String name : OreDictionary.getOreNames()) + for( String name : OreDictionary.getOreNames() ) { - if ( name != null && this.shouldCare( name ) ) + if( name != null && this.shouldCare( name ) ) { - for (ItemStack item : OreDictionary.getOres( name )) + for( ItemStack item : OreDictionary.getOres( name ) ) { - if ( item != null ) + if( item != null ) n.oreRegistered( name, item ); } } } } - - public void bakeRecipes() - { - this.enableRebaking = true; - - for (Object o : CraftingManager.getInstance().getRecipeList()) - { - if ( o instanceof IRecipeBakeable ) - { - try - { - ((IRecipeBakeable) o).bake(); - } - catch (Throwable e) - { - AELog.error( e ); - } - } - } - } - } diff --git a/src/main/java/appeng/server/AECommand.java b/src/main/java/appeng/server/AECommand.java index f08e31751..60cd60912 100644 --- a/src/main/java/appeng/server/AECommand.java +++ b/src/main/java/appeng/server/AECommand.java @@ -18,22 +18,40 @@ package appeng.server; -import com.google.common.base.Joiner; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.command.WrongUsageException; import net.minecraft.server.MinecraftServer; +import com.google.common.base.Joiner; + + public class AECommand extends CommandBase { final MinecraftServer srv; - public AECommand(MinecraftServer server) { + public AECommand( MinecraftServer server ) + { this.srv = server; } + @Override + public int getRequiredPermissionLevel() + { + return 0; + } + + /** + * wtf? + */ + @Override + public int compareTo( Object arg0 ) + { + return 1; + } + @Override public String getCommandName() { @@ -41,44 +59,38 @@ public class AECommand extends CommandBase } @Override - public String getCommandUsage(ICommandSender icommandsender) + public String getCommandUsage( ICommandSender icommandsender ) { return "commands.ae2.usage"; } @Override - public int getRequiredPermissionLevel() + public void processCommand( ICommandSender sender, String[] args ) { - return 0; - } - - @Override - public void processCommand(ICommandSender sender, String[] args) - { - if ( args.length == 0 ) + if( args.length == 0 ) { throw new WrongUsageException( "commands.ae2.usage" ); } - else if ( "help".equals( args[0] ) ) + else if( "help".equals( args[0] ) ) { try { - if ( args.length > 1 ) + if( args.length > 1 ) { Commands c = Commands.valueOf( args[1] ); throw new WrongUsageException( c.command.getHelp( this.srv ) ); } } - catch ( WrongUsageException wrong ) + catch( WrongUsageException wrong ) { throw wrong; } - catch (Throwable er) + catch( Throwable er ) { throw new WrongUsageException( "commands.ae2.usage" ); } } - else if ( "list".equals( args[0] ) ) + else if( "list".equals( args[0] ) ) { throw new WrongUsageException( Joiner.on( ", " ).join( Commands.values() ) ); } @@ -87,28 +99,19 @@ public class AECommand extends CommandBase try { Commands c = Commands.valueOf( args[0] ); - if ( sender.canCommandSenderUseCommand( c.level, this.getCommandName() ) ) + if( sender.canCommandSenderUseCommand( c.level, this.getCommandName() ) ) c.command.call( this.srv, args, sender ); else throw new WrongUsageException( "commands.ae2.permissions" ); } - catch ( WrongUsageException wrong ) + catch( WrongUsageException wrong ) { throw wrong; } - catch (Throwable er) + catch( Throwable er ) { throw new WrongUsageException( "commands.ae2.usage" ); } } } - - /** - * wtf? - */ - @Override - public int compareTo(Object arg0) - { - return 1; - } } diff --git a/src/main/java/appeng/server/AccessType.java b/src/main/java/appeng/server/AccessType.java index 737359f31..0d45762ae 100644 --- a/src/main/java/appeng/server/AccessType.java +++ b/src/main/java/appeng/server/AccessType.java @@ -18,6 +18,7 @@ package appeng.server; + public enum AccessType { /** diff --git a/src/main/java/appeng/server/Commands.java b/src/main/java/appeng/server/Commands.java index d596d0750..6b7267011 100644 --- a/src/main/java/appeng/server/Commands.java +++ b/src/main/java/appeng/server/Commands.java @@ -18,25 +18,28 @@ package appeng.server; + import appeng.server.subcommands.ChunkLogger; import appeng.server.subcommands.Supporters; + public enum Commands { - Chunklogger(4, new ChunkLogger()), supporters(0, new Supporters()); + Chunklogger( 4, new ChunkLogger() ), supporters( 0, new Supporters() ); public final int level; public final ISubCommand command; + Commands( int level, ISubCommand w ) + { + this.level = level; + this.command = w; + } + @Override public String toString() { return this.name(); } - Commands( int level, ISubCommand w ) { - this.level = level; - this.command = w; - } - } diff --git a/src/main/java/appeng/server/ISubCommand.java b/src/main/java/appeng/server/ISubCommand.java index c7ff75510..4abd9ddec 100644 --- a/src/main/java/appeng/server/ISubCommand.java +++ b/src/main/java/appeng/server/ISubCommand.java @@ -18,14 +18,15 @@ package appeng.server; + import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; + public interface ISubCommand { - String getHelp(MinecraftServer srv); - - void call(MinecraftServer srv, String[] args, ICommandSender sender); + String getHelp( MinecraftServer srv ); + void call( MinecraftServer srv, String[] args, ICommandSender sender ); } diff --git a/src/main/java/appeng/server/ServerHelper.java b/src/main/java/appeng/server/ServerHelper.java index 8076fc345..4d7585161 100644 --- a/src/main/java/appeng/server/ServerHelper.java +++ b/src/main/java/appeng/server/ServerHelper.java @@ -18,6 +18,7 @@ package appeng.server; + import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -42,52 +43,11 @@ import appeng.core.sync.network.NetworkHandler; import appeng.items.tools.ToolNetworkTool; import appeng.util.Platform; + public class ServerHelper extends CommonHelper { - @Override - public void doRenderItem(ItemStack sis, World tile) - { - - } - - @Override - public List getPlayers() - { - if ( !Platform.isClient() ) - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - - if ( server != null ) - return server.getConfigurationManager().playerEntityList; - } - - return new ArrayList(); - } - - @Override - public void sendToAllNearExcept(EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet) - { - if ( Platform.isClient() ) - return; - - for (EntityPlayer o : this.getPlayers()) - { - EntityPlayerMP entityplayermp = (EntityPlayerMP) o; - - if ( entityplayermp != p && entityplayermp.worldObj == w ) - { - double dX = x - entityplayermp.posX; - double dY = y - entityplayermp.posY; - double dZ = z - entityplayermp.posZ; - - if ( dX * dX + dY * dY + dZ * dZ < dist * dist ) - { - NetworkHandler.instance.sendTo( packet, entityplayermp ); - } - } - } - } + private EntityPlayer renderModeBased; @Override public void init() @@ -95,12 +55,6 @@ public class ServerHelper extends CommonHelper } - @Override - public void postInit() - { - - } - @Override public World getWorld() { @@ -108,19 +62,57 @@ public class ServerHelper extends CommonHelper } @Override - public void bindTileEntitySpecialRenderer(Class tile, AEBaseBlock blk) + public void bindTileEntitySpecialRenderer( Class tile, AEBaseBlock blk ) { throw new RuntimeException( "This is a server..." ); } @Override - public void spawnEffect(EffectType type, World worldObj, double posX, double posY, double posZ, Object o) + public List getPlayers() + { + if( !Platform.isClient() ) + { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + + if( server != null ) + return server.getConfigurationManager().playerEntityList; + } + + return new ArrayList(); + } + + @Override + public void sendToAllNearExcept( EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet ) + { + if( Platform.isClient() ) + return; + + for( EntityPlayer o : this.getPlayers() ) + { + EntityPlayerMP entityplayermp = (EntityPlayerMP) o; + + if( entityplayermp != p && entityplayermp.worldObj == w ) + { + double dX = x - entityplayermp.posX; + double dY = y - entityplayermp.posY; + double dZ = z - entityplayermp.posZ; + + if( dX * dX + dY * dY + dZ * dZ < dist * dist ) + { + NetworkHandler.instance.sendTo( packet, entityplayermp ); + } + } + } + } + + @Override + public void spawnEffect( EffectType type, World worldObj, double posX, double posY, double posZ, Object o ) { // :P } @Override - public boolean shouldAddParticles(Random r) + public boolean shouldAddParticles( Random r ) { return false; } @@ -131,35 +123,39 @@ public class ServerHelper extends CommonHelper return null; } + @Override + public void doRenderItem( ItemStack sis, World tile ) + { + + } + + @Override + public void postInit() + { + + } + @Override public CableRenderMode getRenderMode() { - if ( this.renderModeBased == null ) + if( this.renderModeBased == null ) return CableRenderMode.Standard; return this.renderModeForPlayer( this.renderModeBased ); } - private EntityPlayer renderModeBased; - - @Override - public void updateRenderMode(EntityPlayer player) + protected CableRenderMode renderModeForPlayer( EntityPlayer player ) { - this.renderModeBased = player; - } - - protected CableRenderMode renderModeForPlayer(EntityPlayer player) - { - if ( player != null ) + if( player != null ) { - for (int x = 0; x < InventoryPlayer.getHotbarSize(); x++) + for( int x = 0; x < InventoryPlayer.getHotbarSize(); x++ ) { ItemStack is = player.inventory.getStackInSlot( x ); - if ( is != null && is.getItem() instanceof ToolNetworkTool ) + if( is != null && is.getItem() instanceof ToolNetworkTool ) { NBTTagCompound c = is.getTagCompound(); - if ( c != null && c.getBoolean( "hideFacades" ) ) + if( c != null && c.getBoolean( "hideFacades" ) ) return CableRenderMode.CableView; } } @@ -174,6 +170,12 @@ public class ServerHelper extends CommonHelper } + @Override + public void updateRenderMode( EntityPlayer player ) + { + this.renderModeBased = player; + } + @Override public void missingCoreMod() { diff --git a/src/main/java/appeng/server/subcommands/ChunkLogger.java b/src/main/java/appeng/server/subcommands/ChunkLogger.java index 1f087b3b5..259568a98 100644 --- a/src/main/java/appeng/server/subcommands/ChunkLogger.java +++ b/src/main/java/appeng/server/subcommands/ChunkLogger.java @@ -32,15 +32,16 @@ import appeng.core.AELog; import appeng.core.features.AEFeature; import appeng.server.ISubCommand; + public class ChunkLogger implements ISubCommand { boolean enabled = false; @SubscribeEvent - public void ChunkLoad(ChunkEvent.Load load) + public void ChunkLoad( ChunkEvent.Load load ) { - if ( !load.world.isRemote ) + if( !load.world.isRemote ) { AELog.info( "Chunk Loaded: " + load.getChunk().xPosition + ", " + load.getChunk().zPosition ); this.displayStack(); @@ -49,12 +50,12 @@ public class ChunkLogger implements ISubCommand private void displayStack() { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.ChunkLoggerTrace ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.ChunkLoggerTrace ) ) { boolean output = false; - for (StackTraceElement e : Thread.currentThread().getStackTrace()) + for( StackTraceElement e : Thread.currentThread().getStackTrace() ) { - if ( output ) + if( output ) AELog.info( " " + e.getClassName() + '.' + e.getMethodName() + " (" + e.getLineNumber() + ')' ); else { @@ -65,9 +66,9 @@ public class ChunkLogger implements ISubCommand } @SubscribeEvent - public void ChunkLoad(ChunkEvent.Unload unload) + public void ChunkLoad( ChunkEvent.Unload unload ) { - if ( !unload.world.isRemote ) + if( !unload.world.isRemote ) { AELog.info( "Chunk Unloaded: " + unload.getChunk().xPosition + ", " + unload.getChunk().zPosition ); this.displayStack(); @@ -75,11 +76,17 @@ public class ChunkLogger implements ISubCommand } @Override - public void call(MinecraftServer srv, String[] data, ICommandSender sender) + public String getHelp( MinecraftServer srv ) + { + return "commands.ae2.ChunkLogger"; + } + + @Override + public void call( MinecraftServer srv, String[] data, ICommandSender sender ) { this.enabled = !this.enabled; - if ( this.enabled ) + if( this.enabled ) { MinecraftForge.EVENT_BUS.register( this ); sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.ChunkLoggerOn" ) ); @@ -90,11 +97,4 @@ public class ChunkLogger implements ISubCommand sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.ChunkLoggerOff" ) ); } } - - @Override - public String getHelp(MinecraftServer srv) - { - return "commands.ae2.ChunkLogger"; - } - } diff --git a/src/main/java/appeng/server/subcommands/Supporters.java b/src/main/java/appeng/server/subcommands/Supporters.java index b2e00cb60..a7d4125b1 100644 --- a/src/main/java/appeng/server/subcommands/Supporters.java +++ b/src/main/java/appeng/server/subcommands/Supporters.java @@ -18,28 +18,29 @@ package appeng.server.subcommands; -import com.google.common.base.Joiner; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; +import com.google.common.base.Joiner; + import appeng.server.ISubCommand; + public class Supporters implements ISubCommand { @Override - public void call(MinecraftServer srv, String[] data, ICommandSender sender) - { - String[] who = { "Stig Halvorsen", "Josh Ricker", "Jenny \"Othlon\" Sutherland", "Hristo Bogdanov", "BevoLJ" }; - sender.addChatMessage( new ChatComponentText( "Special thanks to " + Joiner.on( ", " ).join( who ) ) ); - } - - @Override - public String getHelp(MinecraftServer srv) + public String getHelp( MinecraftServer srv ) { return "commands.ae2.Supporters"; } + @Override + public void call( MinecraftServer srv, String[] data, ICommandSender sender ) + { + String[] who = { "Stig Halvorsen", "Josh Ricker", "Jenny \"Othlon\" Sutherland", "Hristo Bogdanov", "BevoLJ" }; + sender.addChatMessage( new ChatComponentText( "Special thanks to " + Joiner.on( ", " ).join( who ) ) ); + } } diff --git a/src/main/java/appeng/services/CompassService.java b/src/main/java/appeng/services/CompassService.java index b6a56665f..de2ad00c0 100644 --- a/src/main/java/appeng/services/CompassService.java +++ b/src/main/java/appeng/services/CompassService.java @@ -66,7 +66,7 @@ public class CompassService implements ThreadFactory public void cleanUp() { - for ( CompassReader cr : this.worldSet.values() ) + for( CompassReader cr : this.worldSet.values() ) cr.close(); } @@ -100,16 +100,16 @@ public class CompassService implements ThreadFactory // lower level... Chunk c = w.getChunkFromBlockCoords( x, z ); - for ( Block skyStoneBlock : AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet() ) + for( Block skyStoneBlock : AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet() ) { - for ( int i = 0; i < CHUNK_SIZE; i++ ) + for( int i = 0; i < CHUNK_SIZE; i++ ) { - for ( int j = 0; j < CHUNK_SIZE; j++ ) + for( int j = 0; j < CHUNK_SIZE; j++ ) { - for ( int k = low_y; k < hi_y; k++ ) + for( int k = low_y; k < hi_y; k++ ) { Block blk = c.getBlock( i, k, j ); - if ( blk == skyStoneBlock && c.getBlockMetadata( i, k, j ) == 0 ) + if( blk == skyStoneBlock && c.getBlockMetadata( i, k, j ) == 0 ) { return this.executor.submit( new CMUpdatePost( w, cx, cz, cdy, true ) ); } @@ -125,7 +125,7 @@ public class CompassService implements ThreadFactory { CompassReader cr = this.worldSet.get( w ); - if ( cr == null ) + if( cr == null ) { cr = new CompassReader( w.provider.dimensionId, this.rootFolder ); this.worldSet.put( w, cr ); @@ -159,14 +159,14 @@ public class CompassService implements ThreadFactory this.executor.awaitTermination( 6, TimeUnit.MINUTES ); this.jobSize = 0; - for ( CompassReader cr : this.worldSet.values() ) + for( CompassReader cr : this.worldSet.values() ) { cr.close(); } this.worldSet.clear(); } - catch ( InterruptedException e ) + catch( InterruptedException e ) { // wrap this up.. } @@ -178,7 +178,6 @@ public class CompassService implements ThreadFactory return new Thread( job, "AE Compass Service" ); } - private class CMUpdatePost implements Runnable { @@ -206,7 +205,7 @@ public class CompassService implements ThreadFactory CompassReader cr = CompassService.this.getReader( this.world ); cr.setHasBeacon( this.chunkX, this.chunkZ, this.doubleChunkY, this.value ); - if ( CompassService.this.jobSize() < 2 ) + if( CompassService.this.jobSize() < 2 ) CompassService.this.cleanUp(); } } @@ -237,18 +236,18 @@ public class CompassService implements ThreadFactory CompassReader cr = CompassService.this.getReader( this.coord.getWorld() ); // Am I standing on it? - if ( cr.hasBeacon( cx, cz ) ) + if( cr.hasBeacon( cx, cz ) ) { this.callback.calculatedDirection( true, true, -999, 0 ); - if ( CompassService.this.jobSize() < 2 ) + if( CompassService.this.jobSize() < 2 ) CompassService.this.cleanUp(); return; } // spiral outward... - for ( int offset = 1; offset < this.maxRange; offset++ ) + for( int offset = 1; offset < this.maxRange; offset++ ) { int minX = cx - offset; int minZ = cz - offset; @@ -259,12 +258,12 @@ public class CompassService implements ThreadFactory int chosen_x = cx; int chosen_z = cz; - for ( int z = minZ; z <= maxZ; z++ ) + for( int z = minZ; z <= maxZ; z++ ) { - if ( cr.hasBeacon( minX, z ) ) + if( cr.hasBeacon( minX, z ) ) { int closeness = CompassService.this.dist( cx, cz, minX, z ); - if ( closeness < closest ) + if( closeness < closest ) { closest = closeness; chosen_x = minX; @@ -272,10 +271,10 @@ public class CompassService implements ThreadFactory } } - if ( cr.hasBeacon( maxX, z ) ) + if( cr.hasBeacon( maxX, z ) ) { int closeness = CompassService.this.dist( cx, cz, maxX, z ); - if ( closeness < closest ) + if( closeness < closest ) { closest = closeness; chosen_x = maxX; @@ -284,12 +283,12 @@ public class CompassService implements ThreadFactory } } - for ( int x = minX + 1; x < maxX; x++ ) + for( int x = minX + 1; x < maxX; x++ ) { - if ( cr.hasBeacon( x, minZ ) ) + if( cr.hasBeacon( x, minZ ) ) { int closeness = CompassService.this.dist( cx, cz, x, minZ ); - if ( closeness < closest ) + if( closeness < closest ) { closest = closeness; chosen_x = x; @@ -297,10 +296,10 @@ public class CompassService implements ThreadFactory } } - if ( cr.hasBeacon( x, maxZ ) ) + if( cr.hasBeacon( x, maxZ ) ) { int closeness = CompassService.this.dist( cx, cz, x, maxZ ); - if ( closeness < closest ) + if( closeness < closest ) { closest = closeness; chosen_x = x; @@ -309,11 +308,11 @@ public class CompassService implements ThreadFactory } } - if ( closest < Integer.MAX_VALUE ) + if( closest < Integer.MAX_VALUE ) { this.callback.calculatedDirection( true, false, CompassService.this.rad( cx, cz, chosen_x, chosen_z ), CompassService.this.dist( cx, cz, chosen_x, chosen_z ) ); - if ( CompassService.this.jobSize() < 2 ) + if( CompassService.this.jobSize() < 2 ) CompassService.this.cleanUp(); return; @@ -323,7 +322,7 @@ public class CompassService implements ThreadFactory // didn't find shit... this.callback.calculatedDirection( false, true, -999, 999 ); - if ( CompassService.this.jobSize() < 2 ) + if( CompassService.this.jobSize() < 2 ) CompassService.this.cleanUp(); } } diff --git a/src/main/java/appeng/services/VersionChecker.java b/src/main/java/appeng/services/VersionChecker.java index 7aa9fc738..57d9093c5 100644 --- a/src/main/java/appeng/services/VersionChecker.java +++ b/src/main/java/appeng/services/VersionChecker.java @@ -29,13 +29,13 @@ import cpw.mods.fml.common.event.FMLInterModComms; import appeng.core.AEConfig; import appeng.core.AELog; import appeng.core.AppEng; -import appeng.services.version.github.FormattedRelease; -import appeng.services.version.github.ReleaseFetcher; import appeng.services.version.ModVersionFetcher; import appeng.services.version.Version; import appeng.services.version.VersionCheckerConfig; import appeng.services.version.VersionFetcher; import appeng.services.version.VersionParser; +import appeng.services.version.github.FormattedRelease; +import appeng.services.version.github.ReleaseFetcher; /** @@ -91,12 +91,12 @@ public final class VersionChecker implements Runnable /** * checks if enough time since last check has expired * - * @param nowInMs now in milli seconds + * @param nowInMs now in milli seconds * @param lastAfterInterval last version check including the interval defined in the config */ private void processInterval( long nowInMs, long lastAfterInterval ) { - if ( nowInMs > lastAfterInterval ) + if( nowInMs > lastAfterInterval ) { final String rawModVersion = AEConfig.VERSION; final VersionParser parser = new VersionParser(); @@ -118,7 +118,7 @@ public final class VersionChecker implements Runnable * Checks if the retrieved version is newer as the current mod version. * Will notify player if config is enabled. * - * @param modVersion version of mod + * @param modVersion version of mod * @param githubRelease release retrieved through github */ private void processVersions( Version modVersion, FormattedRelease githubRelease ) @@ -127,15 +127,15 @@ public final class VersionChecker implements Runnable final String modFormatted = modVersion.formatted(); final String ghFormatted = githubVersion.formatted(); - if ( githubVersion.isNewerAs( modVersion ) ) + if( githubVersion.isNewerAs( modVersion ) ) { final String changelog = githubRelease.changelog(); - if ( this.config.shouldNotifyPlayer() ) + if( this.config.shouldNotifyPlayer() ) { AELog.info( "Newer version is available: " + ghFormatted + " (found) > " + modFormatted + " (current)" ); - if ( this.config.shouldPostChangelog() ) + if( this.config.shouldPostChangelog() ) { AELog.info( "Changelog: " + changelog ); } @@ -145,7 +145,7 @@ public final class VersionChecker implements Runnable } else { - AELog.info( "No newer version is available: " + ghFormatted + "(found) < " + modFormatted + " (current)"); + AELog.info( "No newer version is available: " + ghFormatted + "(found) < " + modFormatted + " (current)" ); } } @@ -153,12 +153,12 @@ public final class VersionChecker implements Runnable * Checks if the version checker mod is installed and handles it depending on that information * * @param modFormatted mod version formatted as rv2-beta-8 - * @param ghFormatted retrieved github version formatted as rv2-beta-8 - * @param changelog retrieved github changelog + * @param ghFormatted retrieved github version formatted as rv2-beta-8 + * @param changelog retrieved github changelog */ private void interactWithVersionCheckerMod( String modFormatted, String ghFormatted, String changelog ) { - if ( Loader.isModLoaded( "VersionChecker" ) ) + if( Loader.isModLoaded( "VersionChecker" ) ) { final NBTTagCompound versionInf = new NBTTagCompound(); versionInf.setString( "modDisplayName", AppEng.MOD_NAME ); @@ -167,7 +167,7 @@ public final class VersionChecker implements Runnable versionInf.setString( "updateUrl", "http://ae-mod.info/builds/appliedenergistics2-" + ghFormatted + ".jar" ); versionInf.setBoolean( "isDirectLink", true ); - if ( !changelog.isEmpty() ) + if( !changelog.isEmpty() ) { versionInf.setString( "changeLog", changelog ); } diff --git a/src/main/java/appeng/services/compass/CompassException.java b/src/main/java/appeng/services/compass/CompassException.java index 55c9453a7..8d700ffd9 100644 --- a/src/main/java/appeng/services/compass/CompassException.java +++ b/src/main/java/appeng/services/compass/CompassException.java @@ -18,6 +18,7 @@ package appeng.services.compass; + public class CompassException extends RuntimeException { @@ -25,8 +26,8 @@ public class CompassException extends RuntimeException public final Throwable inner; - public CompassException(Throwable t) { + public CompassException( Throwable t ) + { this.inner = t; } - } diff --git a/src/main/java/appeng/services/compass/CompassReader.java b/src/main/java/appeng/services/compass/CompassReader.java index 71f9227d0..676d88262 100644 --- a/src/main/java/appeng/services/compass/CompassReader.java +++ b/src/main/java/appeng/services/compass/CompassReader.java @@ -18,6 +18,7 @@ package appeng.services.compass; + import java.io.File; import java.util.HashMap; @@ -28,9 +29,15 @@ public class CompassReader private final int dimensionId; private final File rootFolder; + public CompassReader( int dimensionId, File rootFolder ) + { + this.dimensionId = dimensionId; + this.rootFolder = rootFolder; + } + public void close() { - for (CompassRegion r : this.regions.values()) + for( CompassRegion r : this.regions.values() ) { r.close(); } @@ -38,39 +45,31 @@ public class CompassReader this.regions.clear(); } - public CompassReader(int dimensionId, File rootFolder) - { - this.dimensionId = dimensionId; - this.rootFolder = rootFolder; - } - - public void setHasBeacon(int cx, int cz, int cdy, boolean hasBeacon) + public void setHasBeacon( int cx, int cz, int cdy, boolean hasBeacon ) { CompassRegion r = this.getRegion( cx, cz ); r.setHasBeacon( cx, cz, cdy, hasBeacon ); } - public boolean hasBeacon(int cx, int cz) - { - CompassRegion r = this.getRegion( cx, cz ); - return r.hasBeacon( cx, cz ); - } - - private CompassRegion getRegion(int cx, int cz) + private CompassRegion getRegion( int cx, int cz ) { long pos = cx >> 10; pos <<= 32; pos |= ( cz >> 10 ); CompassRegion cr = this.regions.get( pos ); - if ( cr == null ) + if( cr == null ) { cr = new CompassRegion( cx, cz, this.dimensionId, this.rootFolder ); this.regions.put( pos, cr ); } return cr; - } + public boolean hasBeacon( int cx, int cz ) + { + CompassRegion r = this.getRegion( cx, cz ); + return r.hasBeacon( cx, cz ); + } } diff --git a/src/main/java/appeng/services/compass/CompassRegion.java b/src/main/java/appeng/services/compass/CompassRegion.java index ba87b0ec5..89d9ec2b0 100644 --- a/src/main/java/appeng/services/compass/CompassRegion.java +++ b/src/main/java/appeng/services/compass/CompassRegion.java @@ -59,11 +59,52 @@ public class CompassRegion this.openFile( false ); } + private void openFile( boolean create ) + { + File fName = this.getFileName(); + if( this.hasFile ) + return; + + if( create || this.fileExists( fName ) ) + { + try + { + this.raf = new RandomAccessFile( fName, "rw" ); + FileChannel fc = this.raf.getChannel(); + this.buffer = fc.map( FileChannel.MapMode.READ_WRITE, 0, 0x400 * 0x400 );// fc.size() ); + this.hasFile = true; + } + catch( Throwable t ) + { + throw new CompassException( t ); + } + } + } + + private File getFileName() + { + String folder = this.rootFolder.getPath() + File.separatorChar + "compass"; + File folderFile = new File( folder ); + + if( !folderFile.exists() || !folderFile.isDirectory() ) + { + if( !folderFile.mkdir() ) + AELog.info( "Failed to create AE2/compass/" ); + } + + return new File( folder, this.world + '_' + this.low_x + '_' + this.low_z + ".dat" ); + } + + private boolean fileExists( File name ) + { + return name.exists() && name.isFile(); + } + public void close() { try { - if ( this.hasFile ) + if( this.hasFile ) { this.buffer = null; this.raf.close(); @@ -71,7 +112,7 @@ public class CompassRegion this.hasFile = false; } } - catch ( Throwable t ) + catch( Throwable t ) { throw new CompassException( t ); } @@ -79,55 +120,19 @@ public class CompassRegion public boolean hasBeacon( int cx, int cz ) { - if ( this.hasFile ) + if( this.hasFile ) { cx &= 0x3FF; cz &= 0x3FF; int val = this.read( cx, cz ); - if ( val != 0 ) + if( val != 0 ) return true; } return false; } - public void setHasBeacon( int cx, int cz, int cdy, boolean hasBeacon ) - { - cx &= 0x3FF; - cz &= 0x3FF; - - this.openFile( hasBeacon ); - - if ( this.hasFile ) - { - int val = this.read( cx, cz ); - int originalVal = val; - - if ( hasBeacon ) - val |= 1 << cdy; - else - val &= ~( 1 << cdy ); - - if ( originalVal != val ) - this.write( cx, cz, val ); - } - } - - private void write( int cx, int cz, int val ) - { - try - { - this.buffer.put( cx + cz * 0x400, ( byte ) val ); - // raf.seek( cx + cz * 0x400 ); - // raf.writeByte( val ); - } - catch ( Throwable t ) - { - throw new CompassException( t ); - } - } - private int read( int cx, int cz ) { try @@ -136,55 +141,49 @@ public class CompassRegion // raf.seek( cx + cz * 0x400 ); // return raf.readByte(); } - catch ( IndexOutOfBoundsException outOfBounds ) + catch( IndexOutOfBoundsException outOfBounds ) { return 0; } - catch ( Throwable t ) + catch( Throwable t ) { throw new CompassException( t ); } } - private void openFile( boolean create ) + public void setHasBeacon( int cx, int cz, int cdy, boolean hasBeacon ) { - File fName = this.getFileName(); - if ( this.hasFile ) - return; + cx &= 0x3FF; + cz &= 0x3FF; - if ( create || this.fileExists( fName ) ) + this.openFile( hasBeacon ); + + if( this.hasFile ) { - try - { - this.raf = new RandomAccessFile( fName, "rw" ); - FileChannel fc = this.raf.getChannel(); - this.buffer = fc.map( FileChannel.MapMode.READ_WRITE, 0, 0x400 * 0x400 );// fc.size() ); - this.hasFile = true; - } - catch ( Throwable t ) - { - throw new CompassException( t ); - } - } + int val = this.read( cx, cz ); + int originalVal = val; + if( hasBeacon ) + val |= 1 << cdy; + else + val &= ~( 1 << cdy ); + + if( originalVal != val ) + this.write( cx, cz, val ); + } } - private boolean fileExists( File name ) + private void write( int cx, int cz, int val ) { - return name.exists() && name.isFile(); - } - - private File getFileName() - { - String folder = this.rootFolder.getPath() + File.separatorChar + "compass"; - File folderFile = new File( folder ); - - if ( !folderFile.exists() || !folderFile.isDirectory() ) + try { - if ( !folderFile.mkdir() ) - AELog.info( "Failed to create AE2/compass/" ); + this.buffer.put( cx + cz * 0x400, (byte) val ); + // raf.seek( cx + cz * 0x400 ); + // raf.writeByte( val ); + } + catch( Throwable t ) + { + throw new CompassException( t ); } - - return new File( folder, this.world + '_' + this.low_x + '_' + this.low_z + ".dat" ); } } diff --git a/src/main/java/appeng/services/compass/ICompassCallback.java b/src/main/java/appeng/services/compass/ICompassCallback.java index 769b9f01a..8eb5d1500 100644 --- a/src/main/java/appeng/services/compass/ICompassCallback.java +++ b/src/main/java/appeng/services/compass/ICompassCallback.java @@ -18,6 +18,7 @@ package appeng.services.compass; + public interface ICompassCallback { @@ -25,10 +26,9 @@ public interface ICompassCallback * Called from another thread. * * @param hasResult true if found a target - * @param spin true if should spin - * @param radians radians - * @param dist distance + * @param spin true if should spin + * @param radians radians + * @param dist distance */ void calculatedDirection( boolean hasResult, boolean spin, double radians, double dist ); - } diff --git a/src/main/java/appeng/services/version/BaseVersion.java b/src/main/java/appeng/services/version/BaseVersion.java index 53625e76f..33dc19682 100644 --- a/src/main/java/appeng/services/version/BaseVersion.java +++ b/src/main/java/appeng/services/version/BaseVersion.java @@ -14,8 +14,8 @@ public abstract class BaseVersion implements Version /** * @param revision revision in natural number - * @param channel channel - * @param build build in natural number + * @param channel channel + * @param build build in natural number * * @throws AssertionError if assertion are enabled and revision or build are not natural numbers */ @@ -65,16 +65,16 @@ public abstract class BaseVersion implements Version @Override public final boolean equals( Object o ) { - if ( this == o ) + if( this == o ) return true; - if ( !( o instanceof Version ) ) + if( !( o instanceof Version ) ) return false; Version that = (Version) o; - if ( this.revision != that.revision() ) + if( this.revision != that.revision() ) return false; - if ( this.build != that.build() ) + if( this.build != that.build() ) return false; return this.channel == that.channel(); } diff --git a/src/main/java/appeng/services/version/DefaultVersion.java b/src/main/java/appeng/services/version/DefaultVersion.java index 5dcaa890b..3c0ad5f3a 100644 --- a/src/main/java/appeng/services/version/DefaultVersion.java +++ b/src/main/java/appeng/services/version/DefaultVersion.java @@ -20,12 +20,12 @@ public final class DefaultVersion extends BaseVersion @Override public boolean isNewerAs( Version maybeOlder ) { - if ( this.revision() > maybeOlder.revision() ) + if( this.revision() > maybeOlder.revision() ) { return true; } - if ( this.channel().compareTo( maybeOlder.channel() ) > 0 ) + if( this.channel().compareTo( maybeOlder.channel() ) > 0 ) { return true; } diff --git a/src/main/java/appeng/services/version/ModVersionFetcher.java b/src/main/java/appeng/services/version/ModVersionFetcher.java index d5eb22a01..a687226a1 100644 --- a/src/main/java/appeng/services/version/ModVersionFetcher.java +++ b/src/main/java/appeng/services/version/ModVersionFetcher.java @@ -25,7 +25,7 @@ public final class ModVersionFetcher implements VersionFetcher @Override public Version get() { - if ( this.rawModVersion.equals( "@version@" ) || this.rawModVersion.contains( "pr" ) ) + if( this.rawModVersion.equals( "@version@" ) || this.rawModVersion.contains( "pr" ) ) { return new DoNotCheckVersion(); } diff --git a/src/main/java/appeng/services/version/VersionParser.java b/src/main/java/appeng/services/version/VersionParser.java index 14cad1147..b1dbc6449 100644 --- a/src/main/java/appeng/services/version/VersionParser.java +++ b/src/main/java/appeng/services/version/VersionParser.java @@ -103,9 +103,9 @@ public final class VersionParser { assert rawChannel.equalsIgnoreCase( Channel.Alpha.name() ) || rawChannel.equalsIgnoreCase( Channel.Beta.name() ) || rawChannel.equalsIgnoreCase( Channel.Release.name() ); - for ( Channel channel : Channel.values() ) + for( Channel channel : Channel.values() ) { - if ( channel.name().equalsIgnoreCase( rawChannel ) ) + if( channel.name().equalsIgnoreCase( rawChannel ) ) { return channel; } diff --git a/src/main/java/appeng/services/version/github/ReleaseFetcher.java b/src/main/java/appeng/services/version/github/ReleaseFetcher.java index 69c70e7a7..d02db488d 100644 --- a/src/main/java/appeng/services/version/github/ReleaseFetcher.java +++ b/src/main/java/appeng/services/version/github/ReleaseFetcher.java @@ -49,7 +49,7 @@ public final class ReleaseFetcher return latestFitRelease; } - catch ( Exception e ) + catch( Exception e ) { AELog.error( e ); @@ -68,14 +68,14 @@ public final class ReleaseFetcher final Channel level = Channel.valueOf( levelInConfig ); final int levelOrdinal = level.ordinal(); - for ( Release release : releases ) + for( Release release : releases ) { final String rawVersion = release.tag_name; final String changelog = release.body; final Version version = this.parser.parse( rawVersion ); - if ( version.channel().ordinal() >= levelOrdinal ) + if( version.channel().ordinal() >= levelOrdinal ) { return new DefaultFormattedRelease( version, changelog ); } diff --git a/src/main/java/appeng/spatial/BiomeGenStorage.java b/src/main/java/appeng/spatial/BiomeGenStorage.java index 2cbd50a0e..4e262b481 100644 --- a/src/main/java/appeng/spatial/BiomeGenStorage.java +++ b/src/main/java/appeng/spatial/BiomeGenStorage.java @@ -18,12 +18,15 @@ package appeng.spatial; + import net.minecraft.world.biome.BiomeGenBase; + public class BiomeGenStorage extends BiomeGenBase { - public BiomeGenStorage(int id) { + public BiomeGenStorage( int id ) + { super( id ); this.setBiomeName( "Storage Cell" ); @@ -39,5 +42,4 @@ public class BiomeGenStorage extends BiomeGenBase this.spawnableWaterCreatureList.clear(); this.spawnableCaveCreatureList.clear(); } - } diff --git a/src/main/java/appeng/spatial/CachedPlane.java b/src/main/java/appeng/spatial/CachedPlane.java index 77779277d..497768861 100644 --- a/src/main/java/appeng/spatial/CachedPlane.java +++ b/src/main/java/appeng/spatial/CachedPlane.java @@ -91,21 +91,21 @@ public class CachedPlane this.myColumns = new Column[this.x_size][this.z_size]; this.verticalBits = 0; - for ( int cy = 0; cy < cy_size; cy++ ) + for( int cy = 0; cy < cy_size; cy++ ) { this.verticalBits |= 1 << ( minCY + cy ); } - for ( int x = 0; x < this.x_size; x++ ) - for ( int z = 0; z < this.z_size; z++ ) + for( int x = 0; x < this.x_size; x++ ) + for( int z = 0; z < this.z_size; z++ ) { this.myColumns[x][z] = new Column( w.getChunkFromChunkCoords( ( minX + x ) >> 4, ( minZ + z ) >> 4 ), ( minX + x ) & 0xF, ( minZ + z ) & 0xF, minCY, cy_size ); } IMovableRegistry mr = AEApi.instance().registries().movable(); - for ( int cx = 0; cx < this.cx_size; cx++ ) - for ( int cz = 0; cz < this.cz_size; cz++ ) + for( int cx = 0; cx < this.cx_size; cx++ ) + for( int cz = 0; cz < this.cz_size; cz++ ) { LinkedList> rawTiles = new LinkedList>(); LinkedList deadTiles = new LinkedList(); @@ -114,13 +114,13 @@ public class CachedPlane this.myChunks[cx][cz] = c; rawTiles.addAll( ( (HashMap) c.chunkTileEntityMap ).entrySet() ); - for ( Entry tx : rawTiles ) + for( Entry tx : rawTiles ) { ChunkPosition cp = tx.getKey(); TileEntity te = tx.getValue(); - if ( te.xCoord >= minX && te.xCoord <= maxX && te.yCoord >= minY && te.yCoord <= maxY && te.zCoord >= minZ && te.zCoord <= maxZ ) + if( te.xCoord >= minX && te.xCoord <= maxX && te.yCoord >= minY && te.yCoord <= maxY && te.zCoord >= minZ && te.zCoord <= maxZ ) { - if ( mr.askToMove( te ) ) + if( mr.askToMove( te ) ) { this.tiles.add( te ); deadTiles.add( cp ); @@ -131,7 +131,7 @@ public class CachedPlane Block blk = (Block) details[0]; // don't skip air, just let the code replace it... - if ( blk != null && blk.isAir( c.worldObj, te.xCoord, te.yCoord, te.zCoord ) && blk.isReplaceable( c.worldObj, te.xCoord, te.yCoord, te.zCoord ) ) + if( blk != null && blk.isAir( c.worldObj, te.xCoord, te.yCoord, te.zCoord ) && blk.isReplaceable( c.worldObj, te.xCoord, te.yCoord, te.zCoord ) ) { c.worldObj.setBlock( te.xCoord, te.yCoord, te.zCoord, Platform.AIR ); c.worldObj.notifyBlocksOfNeighborChange( te.xCoord, te.yCoord, te.zCoord, Platform.AIR ); @@ -142,19 +142,19 @@ public class CachedPlane } } - for ( ChunkPosition cp : deadTiles ) + for( ChunkPosition cp : deadTiles ) { c.chunkTileEntityMap.remove( cp ); } long k = this.world.getTotalWorldTime(); List list = this.world.getPendingBlockUpdates( c, false ); - if ( list != null ) + if( list != null ) { - for ( Object o : list ) + for( Object o : list ) { NextTickListEntry entry = (NextTickListEntry) o; - if ( entry.xCoord >= minX && entry.xCoord <= maxX && entry.yCoord >= minY && entry.yCoord <= maxY && entry.zCoord >= minZ && entry.zCoord <= maxZ ) + if( entry.xCoord >= minX && entry.xCoord <= maxX && entry.yCoord >= minY && entry.yCoord <= maxY && entry.zCoord >= minZ && entry.zCoord <= maxZ ) { NextTickListEntry newEntry = new NextTickListEntry( entry.xCoord, entry.yCoord, entry.zCoord, entry.func_151351_a() ); newEntry.scheduledTime = entry.scheduledTime - k; @@ -164,13 +164,13 @@ public class CachedPlane } } - for ( TileEntity te : this.tiles ) + for( TileEntity te : this.tiles ) { try { this.world.loadedTileEntityList.remove( te ); } - catch ( Exception e ) + catch( Exception e ) { AELog.error( e ); } @@ -187,25 +187,25 @@ public class CachedPlane { IMovableRegistry mr = AEApi.instance().registries().movable(); - if ( dst.x_size == this.x_size && dst.y_size == this.y_size && dst.z_size == this.z_size ) + if( dst.x_size == this.x_size && dst.y_size == this.y_size && dst.z_size == this.z_size ) { AELog.info( "Block Copy Scale: " + this.x_size + ", " + this.y_size + ", " + this.z_size ); long startTime = System.nanoTime(); - for ( int x = 0; x < this.x_size; x++ ) + for( int x = 0; x < this.x_size; x++ ) { - for ( int z = 0; z < this.z_size; z++ ) + for( int z = 0; z < this.z_size; z++ ) { Column a = this.myColumns[x][z]; Column b = dst.myColumns[x][z]; - for ( int y = 0; y < this.y_size; y++ ) + for( int y = 0; y < this.y_size; y++ ) { int src_y = y + this.y_offset; int dst_y = y + dst.y_offset; - if ( a.doNotSkip( src_y ) && b.doNotSkip( dst_y ) ) + if( a.doNotSkip( src_y ) && b.doNotSkip( dst_y ) ) { Object[] aD = a.getDetails( src_y ); Object[] bD = b.getDetails( dst_y ); @@ -226,22 +226,22 @@ public class CachedPlane long duration = endTime - startTime; AELog.info( "Block Copy Time: " + duration ); - for ( TileEntity te : this.tiles ) + for( TileEntity te : this.tiles ) { dst.addTile( te.xCoord - this.x_offset, te.yCoord - this.y_offset, te.zCoord - this.z_offset, te, this, mr ); } - for ( TileEntity te : dst.tiles ) + for( TileEntity te : dst.tiles ) { this.addTile( te.xCoord - dst.x_offset, te.yCoord - dst.y_offset, te.zCoord - dst.z_offset, te, dst, mr ); } - for ( NextTickListEntry entry : this.ticks ) + for( NextTickListEntry entry : this.ticks ) { dst.addTick( entry.xCoord - this.x_offset, entry.yCoord - this.y_offset, entry.zCoord - this.z_offset, entry ); } - for ( NextTickListEntry entry : dst.ticks ) + for( NextTickListEntry entry : dst.ticks ) { this.addTick( entry.xCoord - dst.x_offset, entry.yCoord - dst.y_offset, entry.zCoord - dst.z_offset, entry ); } @@ -259,7 +259,7 @@ public class CachedPlane private void markForUpdate( int src_x, int src_y, int src_z ) { this.updates.add( new WorldCoord( src_x, src_y, src_z ) ); - for ( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) this.updates.add( new WorldCoord( src_x + d.offsetX, src_y + d.offsetY, src_z + d.offsetZ ) ); } @@ -274,7 +274,7 @@ public class CachedPlane { Column c = this.myColumns[x][z]; - if ( c.doNotSkip( y + this.y_offset ) || alternateDestination == null ) + if( c.doNotSkip( y + this.y_offset ) || alternateDestination == null ) { IMovableHandler handler = this.getHandler( te ); @@ -282,7 +282,7 @@ public class CachedPlane { handler.moveTile( te, this.world, x + this.x_offset, y + this.y_offset, z + this.z_offset ); } - catch ( Throwable e ) + catch( Throwable e ) { AELog.error( e ); @@ -295,7 +295,7 @@ public class CachedPlane c.c.func_150812_a( c.x, y + y, c.z, te ); // c.c.setChunkTileEntity( c.x, y + y, c.z, te ); - if ( c.c.isChunkLoaded ) + if( c.c.isChunkLoaded ) { this.world.addTileEntity( te ); this.world.markBlockForUpdate( x, y, z ); @@ -309,7 +309,7 @@ public class CachedPlane alternateDestination.addTile( x, y, z, te, null, mr ); } } - catch ( Throwable e ) + catch( Throwable e ) { AELog.error( e ); } @@ -319,8 +319,8 @@ public class CachedPlane { // update shit.. - for ( int x = 0; x < this.cx_size; x++ ) - for ( int z = 0; z < this.cz_size; z++ ) + for( int x = 0; x < this.cx_size; x++ ) + for( int z = 0; z < this.cz_size; z++ ) { Chunk c = this.myChunks[x][z]; c.resetRelightChecks(); @@ -329,20 +329,19 @@ public class CachedPlane } // send shit... - for ( int x = 0; x < this.cx_size; x++ ) - for ( int z = 0; z < this.cz_size; z++ ) + for( int x = 0; x < this.cx_size; x++ ) + for( int z = 0; z < this.cz_size; z++ ) { Chunk c = this.myChunks[x][z]; - for ( int y = 1; y < 255; y += 32 ) + for( int y = 1; y < 255; y += 32 ) WorldSettings.getInstance().getCompass().updateArea( this.world, c.xPosition << 4, y, c.zPosition << 4 ); Platform.sendChunk( c, this.verticalBits ); } } - class Column { @@ -361,20 +360,20 @@ public class CachedPlane this.storage = this.c.getBlockStorageArray(); // make sure storage exists before hand... - for ( int ay = 0; ay < chunkHeight; ay++ ) + for( int ay = 0; ay < chunkHeight; ay++ ) { int by = ( ay + cy ); ExtendedBlockStorage extendedblockstorage = this.storage[by]; - if ( extendedblockstorage == null ) + if( extendedblockstorage == null ) extendedblockstorage = this.storage[by] = new ExtendedBlockStorage( by << 4, !this.c.worldObj.provider.hasNoSky ); } } public void setBlockIDWithMetadata( int y, Object[] blk ) { - for ( Block matrixFrameBlock : CachedPlane.this.matrixFrame.maybeBlock().asSet() ) + for( Block matrixFrameBlock : CachedPlane.this.matrixFrame.maybeBlock().asSet() ) { - if ( blk[0] == matrixFrameBlock ) + if( blk[0] == matrixFrameBlock ) { blk[0] = Platform.AIR; } @@ -399,7 +398,7 @@ public class CachedPlane public boolean doNotSkip( int y ) { ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; - if ( CachedPlane.this.reg.isBlacklisted( extendedblockstorage.getBlockByExtId( this.x, y & 15, this.z ) ) ) + if( CachedPlane.this.reg.isBlacklisted( extendedblockstorage.getBlockByExtId( this.x, y & 15, this.z ) ) ) return false; return this.skipThese == null || !this.skipThese.contains( y ); @@ -407,7 +406,7 @@ public class CachedPlane public void setSkip( int yCoord ) { - if ( this.skipThese == null ) + if( this.skipThese == null ) this.skipThese = new LinkedList(); this.skipThese.add( yCoord ); } diff --git a/src/main/java/appeng/spatial/DefaultSpatialHandler.java b/src/main/java/appeng/spatial/DefaultSpatialHandler.java index 04e3f77e2..862a43bf4 100644 --- a/src/main/java/appeng/spatial/DefaultSpatialHandler.java +++ b/src/main/java/appeng/spatial/DefaultSpatialHandler.java @@ -18,17 +18,32 @@ package appeng.spatial; + import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import appeng.api.movable.IMovableHandler; + public class DefaultSpatialHandler implements IMovableHandler { + /** + * never called for the default. + * + * @param tile tile entity + * + * @return true + */ @Override - public void moveTile(TileEntity te, World w, int x, int y, int z) + public boolean canHandle( Class myClass, TileEntity tile ) + { + return true; + } + + @Override + public void moveTile( TileEntity te, World w, int x, int y, int z ) { te.setWorldObj( w ); @@ -40,23 +55,10 @@ public class DefaultSpatialHandler implements IMovableHandler c.func_150812_a( x & 0xF, y, z & 0xF, te ); // c.setChunkBlockTileEntity( x & 0xF, y, z & 0xF, te ); - if ( c.isChunkLoaded ) + if( c.isChunkLoaded ) { w.addTileEntity( te ); w.markBlockForUpdate( x, y, z ); } } - - /** - * never called for the default. - * - * @param tile tile entity - * @return true - */ - @Override - public boolean canHandle(Class myClass, TileEntity tile) - { - return true; - } - } diff --git a/src/main/java/appeng/spatial/ISpatialVisitor.java b/src/main/java/appeng/spatial/ISpatialVisitor.java index 7ec906084..204bde08c 100644 --- a/src/main/java/appeng/spatial/ISpatialVisitor.java +++ b/src/main/java/appeng/spatial/ISpatialVisitor.java @@ -18,9 +18,9 @@ package appeng.spatial; + public interface ISpatialVisitor { - void visit(int x, int y, int z); - + void visit( int x, int y, int z ); } diff --git a/src/main/java/appeng/spatial/StorageChunkProvider.java b/src/main/java/appeng/spatial/StorageChunkProvider.java index 4cce6d560..82172cab7 100644 --- a/src/main/java/appeng/spatial/StorageChunkProvider.java +++ b/src/main/java/appeng/spatial/StorageChunkProvider.java @@ -42,9 +42,9 @@ public class StorageChunkProvider extends ChunkProviderGenerate { BLOCKS = new Block[255 * SQUARE_CHUNK_SIZE]; - for ( Block matrixFrameBlock : AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().asSet() ) + for( Block matrixFrameBlock : AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().asSet() ) { - for ( int x = 0; x < BLOCKS.length; x++ ) + for( int x = 0; x < BLOCKS.length; x++ ) { BLOCKS[x] = matrixFrameBlock; } @@ -67,10 +67,10 @@ public class StorageChunkProvider extends ChunkProviderGenerate byte[] biomes = chunk.getBiomeArray(); AEConfig config = AEConfig.instance; - for ( int k = 0; k < biomes.length; ++k ) + for( int k = 0; k < biomes.length; ++k ) biomes[k] = (byte) config.storageBiomeID; - if ( !chunk.isTerrainPopulated ) + if( !chunk.isTerrainPopulated ) { chunk.isTerrainPopulated = true; chunk.resetRelightChecks(); diff --git a/src/main/java/appeng/spatial/StorageHelper.java b/src/main/java/appeng/spatial/StorageHelper.java index aff2b339e..a441eeb6c 100644 --- a/src/main/java/appeng/spatial/StorageHelper.java +++ b/src/main/java/appeng/spatial/StorageHelper.java @@ -18,6 +18,7 @@ package appeng.spatial; + import java.lang.reflect.Method; import java.util.List; @@ -37,125 +38,29 @@ import appeng.api.util.WorldCoord; import appeng.core.stats.Achievements; import appeng.util.Platform; + public class StorageHelper { private static StorageHelper instance; + Method onEntityRemoved; public static StorageHelper getInstance() { - if ( instance == null ) + if( instance == null ) instance = new StorageHelper(); return instance; } - static class TriggerUpdates implements ISpatialVisitor - { - - final World dst; - - public TriggerUpdates(World dst2) { - this.dst = dst2; - } - - @Override - public void visit(int x, int y, int z) - { - Block blk = this.dst.getBlock( x, y, z ); - blk.onNeighborBlockChange( this.dst, x, y, z, Platform.AIR ); - } - } - - static class WrapInMatrixFrame implements ISpatialVisitor - { - - final World dst; - final Block blkID; - final int Meta; - - public WrapInMatrixFrame(Block blockID, int metaData, World dst2) { - this.dst = dst2; - this.blkID = blockID; - this.Meta = metaData; - } - - @Override - public void visit(int x, int y, int z) - { - this.dst.setBlock( x, y, z, this.blkID, this.Meta, 3 ); - } - } - - static class TelDestination - { - - TelDestination(World _dim, AxisAlignedBB srcBox, double _x, double _y, double _z, int tileX, int tileY, int tileZ) { - this.dim = _dim; - this.x = Math.min( srcBox.maxX - 0.5, Math.max( srcBox.minX + 0.5, _x + tileX ) ); - this.y = Math.min( srcBox.maxY - 0.5, Math.max( srcBox.minY + 0.5, _y + tileY ) ); - this.z = Math.min( srcBox.maxZ - 0.5, Math.max( srcBox.minZ + 0.5, _z + tileZ ) ); - this.xOff = tileX; - this.yOff = tileY; - this.zOff = tileZ; - } - - final World dim; - final double x; - final double y; - final double z; - - final int xOff; - final int yOff; - final int zOff; - } - - static class METeleporter extends Teleporter - { - - final TelDestination destination; - - public METeleporter(WorldServer par1WorldServer, TelDestination d) { - super( par1WorldServer ); - this.destination = d; - } - - @Override - public void placeInPortal(Entity par1Entity, double par2, double par4, double par6, float par8) - { - par1Entity.setLocationAndAngles( this.destination.x, this.destination.y, this.destination.z, par1Entity.rotationYaw, 0.0F ); - par1Entity.motionX = par1Entity.motionY = par1Entity.motionZ = 0.0D; - } - - @Override - public boolean makePortal(Entity par1Entity) - { - return false; - } - - @Override - public boolean placeInExistingPortal(Entity par1Entity, double par2, double par4, double par6, float par8) - { - return false; - } - - @Override - public void removeStalePortalLocations(long par1) - { - - } - - } - - Method onEntityRemoved; - /** * Mostly from dimensional doors.. which mostly got it form X-Comp. * * @param entity to be teleported entity - * @param link destination + * @param link destination + * * @return teleported entity */ - public Entity teleportEntity(Entity entity, TelDestination link) + public Entity teleportEntity( Entity entity, TelDestination link ) { WorldServer oldWorld; WorldServer newWorld; @@ -165,26 +70,26 @@ public class StorageHelper { oldWorld = (WorldServer) entity.worldObj; newWorld = (WorldServer) link.dim; - player = (entity instanceof EntityPlayerMP) ? (EntityPlayerMP) entity : null; + player = ( entity instanceof EntityPlayerMP ) ? (EntityPlayerMP) entity : null; } - catch (Throwable e) + catch( Throwable e ) { return entity; } - if ( oldWorld == null ) + if( oldWorld == null ) return entity; - if ( newWorld == null ) + if( newWorld == null ) return entity; // Is something riding? Handle it first. - if ( entity.riddenByEntity != null ) + if( entity.riddenByEntity != null ) { return this.teleportEntity( entity.riddenByEntity, link ); } // Are we riding something? Dismount and tell the mount to go first. Entity cart = entity.ridingEntity; - if ( cart != null ) + if( cart != null ) { entity.mountEntity( null ); cart = this.teleportEntity( cart, link ); @@ -195,11 +100,11 @@ public class StorageHelper WorldServer.class.cast( newWorld ).getChunkProvider().loadChunk( MathHelper.floor_double( link.x ) >> 4, MathHelper.floor_double( link.z ) >> 4 ); boolean diffDestination = newWorld != oldWorld; - if ( diffDestination ) + if( diffDestination ) { - if ( player != null ) + if( player != null ) { - if ( link.dim.provider instanceof StorageWorldProvider ) + if( link.dim.provider instanceof StorageWorldProvider ) Achievements.SpatialIOExplorer.addToPlayer( player ); player.mcServer.getConfigurationManager().transferPlayerToDimension( player, link.dim.provider.dimensionId, new METeleporter( newWorld, link ) ); @@ -209,20 +114,20 @@ public class StorageHelper int entX = entity.chunkCoordX; int entZ = entity.chunkCoordZ; - if ( (entity.addedToChunk) && (oldWorld.getChunkProvider().chunkExists( entX, entZ )) ) + if( ( entity.addedToChunk ) && ( oldWorld.getChunkProvider().chunkExists( entX, entZ ) ) ) { oldWorld.getChunkFromChunkCoords( entX, entZ ).removeEntity( entity ); oldWorld.getChunkFromChunkCoords( entX, entZ ).isModified = true; } Entity newEntity = EntityList.createEntityByName( EntityList.getEntityString( entity ), newWorld ); - if ( newEntity != null ) + if( newEntity != null ) { entity.lastTickPosX = entity.prevPosX = entity.posX = link.x; entity.lastTickPosY = entity.prevPosY = entity.posY = link.y; entity.lastTickPosZ = entity.prevPosZ = entity.posZ = link.z; - if ( entity instanceof EntityHanging ) + if( entity instanceof EntityHanging ) { EntityHanging h = (EntityHanging) entity; h.field_146063_b += link.xOff; @@ -249,9 +154,9 @@ public class StorageHelper entity.worldObj.updateEntityWithOptionalForce( entity, false ); - if ( cart != null ) + if( cart != null ) { - if ( player != null ) + if( player != null ) entity.worldObj.updateEntityWithOptionalForce( entity, true ); entity.mountEntity( cart ); @@ -260,36 +165,33 @@ public class StorageHelper return entity; } - public void transverseEdges(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, ISpatialVisitor visitor) + public void transverseEdges( int minX, int minY, int minZ, int maxX, int maxY, int maxZ, ISpatialVisitor visitor ) { - for (int y = minY; y < maxY; y++) - for (int z = minZ; z < maxZ; z++) + for( int y = minY; y < maxY; y++ ) + for( int z = minZ; z < maxZ; z++ ) { visitor.visit( minX, y, z ); visitor.visit( maxX, y, z ); } - for (int x = minX; x < maxX; x++) - for (int z = minZ; z < maxZ; z++) + for( int x = minX; x < maxX; x++ ) + for( int z = minZ; z < maxZ; z++ ) { visitor.visit( x, minY, z ); visitor.visit( x, maxY, z ); } - for (int x = minX; x < maxX; x++) - for (int y = minY; y < maxY; y++) + for( int x = minX; x < maxX; x++ ) + for( int y = minY; y < maxY; y++ ) { visitor.visit( x, y, minZ ); visitor.visit( x, y, maxZ ); } - } - public void swapRegions(World src /** over world **/ - , World dst /** storage cell **/ - , int x, int y, int z, int i, int j, int k, int scaleX, int scaleY, int scaleZ) + public void swapRegions( World src /** over world **/, World dst /** storage cell **/, int x, int y, int z, int i, int j, int k, int scaleX, int scaleY, int scaleZ ) { - for ( Block matrixFrameBlock : AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().asSet() ) + for( Block matrixFrameBlock : AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().asSet() ) { this.transverseEdges( i - 1, j - 1, k - 1, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1, new WrapInMatrixFrame( matrixFrameBlock, 0, dst ) ); } @@ -307,20 +209,20 @@ public class StorageHelper List srcE = src.getEntitiesWithinAABB( Entity.class, srcBox ); List dstE = dst.getEntitiesWithinAABB( Entity.class, dstBox ); - for (Entity e : dstE) + for( Entity e : dstE ) { this.teleportEntity( e, new TelDestination( src, srcBox, e.posX, e.posY, e.posZ, -i + x, -j + y, -k + z ) ); } - for (Entity e : srcE) + for( Entity e : srcE ) { this.teleportEntity( e, new TelDestination( dst, dstBox, e.posX, e.posY, e.posZ, -x + i, -y + j, -z + k ) ); } - for (WorldCoord wc : cDst.updates) + for( WorldCoord wc : cDst.updates ) cDst.world.notifyBlockOfNeighborChange( wc.x, wc.y, wc.z, Platform.AIR ); - for (WorldCoord wc : cSrc.updates) + for( WorldCoord wc : cSrc.updates ) cSrc.world.notifyBlockOfNeighborChange( wc.x, wc.y, wc.z, Platform.AIR ); this.transverseEdges( x - 1, y - 1, z - 1, x + scaleX + 1, y + scaleY + 1, z + scaleZ + 1, new TriggerUpdates( src ) ); @@ -338,4 +240,105 @@ public class StorageHelper } + static class TriggerUpdates implements ISpatialVisitor + { + + final World dst; + + public TriggerUpdates( World dst2 ) + { + this.dst = dst2; + } + + @Override + public void visit( int x, int y, int z ) + { + Block blk = this.dst.getBlock( x, y, z ); + blk.onNeighborBlockChange( this.dst, x, y, z, Platform.AIR ); + } + } + + + static class WrapInMatrixFrame implements ISpatialVisitor + { + + final World dst; + final Block blkID; + final int Meta; + + public WrapInMatrixFrame( Block blockID, int metaData, World dst2 ) + { + this.dst = dst2; + this.blkID = blockID; + this.Meta = metaData; + } + + @Override + public void visit( int x, int y, int z ) + { + this.dst.setBlock( x, y, z, this.blkID, this.Meta, 3 ); + } + } + + + static class TelDestination + { + + final World dim; + final double x; + final double y; + final double z; + final int xOff; + final int yOff; + final int zOff; + + TelDestination( World _dim, AxisAlignedBB srcBox, double _x, double _y, double _z, int tileX, int tileY, int tileZ ) + { + this.dim = _dim; + this.x = Math.min( srcBox.maxX - 0.5, Math.max( srcBox.minX + 0.5, _x + tileX ) ); + this.y = Math.min( srcBox.maxY - 0.5, Math.max( srcBox.minY + 0.5, _y + tileY ) ); + this.z = Math.min( srcBox.maxZ - 0.5, Math.max( srcBox.minZ + 0.5, _z + tileZ ) ); + this.xOff = tileX; + this.yOff = tileY; + this.zOff = tileZ; + } + } + + + static class METeleporter extends Teleporter + { + + final TelDestination destination; + + public METeleporter( WorldServer par1WorldServer, TelDestination d ) + { + super( par1WorldServer ); + this.destination = d; + } + + @Override + public void placeInPortal( Entity par1Entity, double par2, double par4, double par6, float par8 ) + { + par1Entity.setLocationAndAngles( this.destination.x, this.destination.y, this.destination.z, par1Entity.rotationYaw, 0.0F ); + par1Entity.motionX = par1Entity.motionY = par1Entity.motionZ = 0.0D; + } + + @Override + public boolean placeInExistingPortal( Entity par1Entity, double par2, double par4, double par6, float par8 ) + { + return false; + } + + @Override + public boolean makePortal( Entity par1Entity ) + { + return false; + } + + @Override + public void removeStalePortalLocations( long par1 ) + { + + } + } } diff --git a/src/main/java/appeng/spatial/StorageWorldProvider.java b/src/main/java/appeng/spatial/StorageWorldProvider.java index 030b1e27c..035676b41 100644 --- a/src/main/java/appeng/spatial/StorageWorldProvider.java +++ b/src/main/java/appeng/spatial/StorageWorldProvider.java @@ -18,6 +18,7 @@ package appeng.spatial; + import net.minecraft.entity.Entity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.Vec3; @@ -33,25 +34,15 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.client.render.SpatialSkyRender; import appeng.core.Registration; + public class StorageWorldProvider extends WorldProvider { - public StorageWorldProvider() { + public StorageWorldProvider() + { this.hasNoSky = true; } - @Override - public ChunkCoordinates getSpawnPoint() - { - return new ChunkCoordinates( 0, 0, 0 ); - } - - @Override - public boolean canRespawnHere() - { - return false; - } - @Override protected void registerWorldChunkManager() { @@ -59,14 +50,13 @@ public class StorageWorldProvider extends WorldProvider } @Override - @SideOnly(Side.CLIENT) - public float[] calcSunriseSunsetColors(float p_76560_1_, float p_76560_2_) + public IChunkProvider createChunkGenerator() { - return null; + return new StorageChunkProvider( this.worldObj, 0 ); } @Override - public float getStarBrightness(float par1) + public float calculateCelestialAngle( long par1, float par3 ) { return 0; } @@ -78,64 +68,35 @@ public class StorageWorldProvider extends WorldProvider } @Override - public boolean canSnowAt(int x, int y, int z, boolean checkLight) + @SideOnly( Side.CLIENT ) + public float[] calcSunriseSunsetColors( float p_76560_1_, float p_76560_2_ ) { - return false; + return null; } @Override - public boolean canDoLightning(Chunk chunk) - { - return false; - } - - @Override - public boolean isBlockHighHumidity(int x, int y, int z) - { - return false; - } - - @Override - public boolean isDaytime() - { - return false; - } - - @Override - public Vec3 getSkyColor(Entity cameraEntity, float partialTicks) + public Vec3 getFogColor( float par1, float par2 ) { return Vec3.createVectorHelper( 0.07, 0.07, 0.07 ); } @Override - public boolean doesXZShowFog(int par1, int par2) + public boolean canRespawnHere() { return false; } @Override - public float calculateCelestialAngle(long par1, float par3) - { - return 0; - } - - @Override - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public boolean isSkyColored() { return true; } @Override - public Vec3 getFogColor(float par1, float par2) + public boolean doesXZShowFog( int par1, int par2 ) { - return Vec3.createVectorHelper( 0.07, 0.07, 0.07 ); - } - - @Override - public IChunkProvider createChunkGenerator() - { - return new StorageChunkProvider( this.worldObj, 0 ); + return false; } @Override @@ -150,4 +111,45 @@ public class StorageWorldProvider extends WorldProvider return SpatialSkyRender.getInstance(); } + @Override + public boolean isDaytime() + { + return false; + } + + @Override + public Vec3 getSkyColor( Entity cameraEntity, float partialTicks ) + { + return Vec3.createVectorHelper( 0.07, 0.07, 0.07 ); + } + + @Override + public float getStarBrightness( float par1 ) + { + return 0; + } + + @Override + public boolean canSnowAt( int x, int y, int z, boolean checkLight ) + { + return false; + } + + @Override + public ChunkCoordinates getSpawnPoint() + { + return new ChunkCoordinates( 0, 0, 0 ); + } + + @Override + public boolean isBlockHighHumidity( int x, int y, int z ) + { + return false; + } + + @Override + public boolean canDoLightning( Chunk chunk ) + { + return false; + } } diff --git a/src/main/java/appeng/tile/AEBaseInvTile.java b/src/main/java/appeng/tile/AEBaseInvTile.java index 84d094ecb..12aa5089f 100644 --- a/src/main/java/appeng/tile/AEBaseInvTile.java +++ b/src/main/java/appeng/tile/AEBaseInvTile.java @@ -18,6 +18,7 @@ package appeng.tile; + import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; @@ -31,31 +32,34 @@ import appeng.tile.events.TileEventType; import appeng.tile.inventory.IAEAppEngInventory; import appeng.tile.inventory.InvOperation; + public abstract class AEBaseInvTile extends AEBaseTile implements ISidedInventory, IAEAppEngInventory { - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_AEBaseInvTile(net.minecraft.nbt.NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_AEBaseInvTile( net.minecraft.nbt.NBTTagCompound data ) { IInventory inv = this.getInternalInventory(); NBTTagCompound opt = data.getCompoundTag( "inv" ); - for (int x = 0; x < inv.getSizeInventory(); x++) + for( int x = 0; x < inv.getSizeInventory(); x++ ) { NBTTagCompound item = opt.getCompoundTag( "item" + x ); inv.setInventorySlotContents( x, ItemStack.loadItemStackFromNBT( item ) ); } } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_AEBaseInvTile(net.minecraft.nbt.NBTTagCompound data) + public abstract IInventory getInternalInventory(); + + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_AEBaseInvTile( net.minecraft.nbt.NBTTagCompound data ) { IInventory inv = this.getInternalInventory(); NBTTagCompound opt = new NBTTagCompound(); - for (int x = 0; x < inv.getSizeInventory(); x++) + for( int x = 0; x < inv.getSizeInventory(); x++ ) { NBTTagCompound item = new NBTTagCompound(); ItemStack is = this.getStackInSlot( x ); - if ( is != null ) + if( is != null ) is.writeToNBT( item ); opt.setTag( "item" + x, item ); } @@ -69,91 +73,29 @@ public abstract class AEBaseInvTile extends AEBaseTile implements ISidedInventor } @Override - public ItemStack getStackInSlot(int i) + public ItemStack getStackInSlot( int i ) { return this.getInternalInventory().getStackInSlot( i ); } @Override - public ItemStack decrStackSize(int i, int j) + public ItemStack decrStackSize( int i, int j ) { return this.getInternalInventory().decrStackSize( i, j ); } @Override - public ItemStack getStackInSlotOnClosing(int i) + public ItemStack getStackInSlotOnClosing( int i ) { return null; } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public void setInventorySlotContents( int i, ItemStack itemstack ) { this.getInternalInventory().setInventorySlotContents( i, itemstack ); } - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public int getInventoryStackLimit() - { - return 64; - } - - @Override - public boolean isUseableByPlayer(EntityPlayer p) - { - final double squaredMCReach = 64.0D; - - return this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord ) == this && p.getDistanceSq( this.xCoord + 0.5D, - this.yCoord + 0.5D, this.zCoord + 0.5D ) <= squaredMCReach; - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) - { - return true; - } - - @Override - public boolean canInsertItem(int slotIndex, ItemStack insertingItem, int side) - { - return this.isItemValidForSlot( slotIndex, insertingItem ); - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side) - { - return true; - } - - public abstract IInventory getInternalInventory(); - - @Override - public abstract void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added); - - public abstract int[] getAccessibleSlotsBySide(ForgeDirection whichSide); - - @Override - final public int[] getAccessibleSlotsFromSide(int side) - { - Block blk = this.worldObj.getBlock( this.xCoord, this.yCoord, this.zCoord ); - if ( blk instanceof AEBaseBlock ) - { - ForgeDirection mySide = ForgeDirection.getOrientation( side ); - return this.getAccessibleSlotsBySide( ((AEBaseBlock) blk).mapRotation( this, mySide ) ); - } - return this.getAccessibleSlotsBySide( ForgeDirection.getOrientation( side ) ); - } - /** * Returns the name of the inventory */ @@ -172,4 +114,62 @@ public abstract class AEBaseInvTile extends AEBaseTile implements ISidedInventor return this.hasCustomName(); } + @Override + public int getInventoryStackLimit() + { + return 64; + } + + @Override + public boolean isUseableByPlayer( EntityPlayer p ) + { + final double squaredMCReach = 64.0D; + + return this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord ) == this && p.getDistanceSq( this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D ) <= squaredMCReach; + } + + @Override + public void openInventory() + { + } + + @Override + public void closeInventory() + { + } + + @Override + public boolean isItemValidForSlot( int i, ItemStack itemstack ) + { + return true; + } + + @Override + public abstract void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ); + + @Override + final public int[] getAccessibleSlotsFromSide( int side ) + { + Block blk = this.worldObj.getBlock( this.xCoord, this.yCoord, this.zCoord ); + if( blk instanceof AEBaseBlock ) + { + ForgeDirection mySide = ForgeDirection.getOrientation( side ); + return this.getAccessibleSlotsBySide( ( (AEBaseBlock) blk ).mapRotation( this, mySide ) ); + } + return this.getAccessibleSlotsBySide( ForgeDirection.getOrientation( side ) ); + } + + @Override + public boolean canInsertItem( int slotIndex, ItemStack insertingItem, int side ) + { + return this.isItemValidForSlot( slotIndex, insertingItem ); + } + + @Override + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) + { + return true; + } + + public abstract int[] getAccessibleSlotsBySide( ForgeDirection whichSide ); } diff --git a/src/main/java/appeng/tile/AEBaseTile.java b/src/main/java/appeng/tile/AEBaseTile.java index c9b33f320..a3ae7c15e 100644 --- a/src/main/java/appeng/tile/AEBaseTile.java +++ b/src/main/java/appeng/tile/AEBaseTile.java @@ -18,6 +18,7 @@ package appeng.tile; + import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.ArrayList; @@ -55,20 +56,21 @@ import appeng.tile.inventory.AppEngInternalAEInventory; import appeng.util.Platform; import appeng.util.SettingsFrom; + public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, ICustomNameObject { + public static final ThreadLocal> DROP_NO_ITEMS = new ThreadLocal>(); static private final HashMap>> HANDLERS = new HashMap>>(); static private final HashMap ITEM_STACKS = new HashMap(); - + public int renderFragment = 0; + public String customName; private ForgeDirection forward = ForgeDirection.UNKNOWN; private ForgeDirection up = ForgeDirection.UNKNOWN; - public static final ThreadLocal> DROP_NO_ITEMS = new ThreadLocal>(); - - public void disableDrops() + static public void registerTileItem( Class c, ItemStackSrc wat ) { - DROP_NO_ITEMS.set( new WeakReference( this ) ); + ITEM_STACKS.put( c, wat ); } public boolean dropItems() @@ -77,9 +79,6 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, return what == null || what.get() != this; } - public int renderFragment = 0; - public String customName; - public boolean notLoaded() { return !this.worldObj.blockExists( this.xCoord, this.yCoord, this.zCoord ); @@ -90,60 +89,104 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, return this; } - static public void registerTileItem(Class c, ItemStackSrc wat) - { - ITEM_STACKS.put( c, wat ); - } - - protected ItemStack getItemFromTile(Object obj) + protected ItemStack getItemFromTile( Object obj ) { ItemStackSrc src = ITEM_STACKS.get( obj.getClass() ); - if ( src == null ) + if( src == null ) return null; return src.stack( 1 ); } - protected boolean hasHandlerFor(TileEventType type) + final public void Tick() { - List list = this.getHandlerListFor( type ); - return list != null && !list.isEmpty(); + } - protected List getHandlerListFor(TileEventType type) + /** + * for dormant chunk cache. + */ + public void onChunkLoad() { - Class clz = this.getClass(); - EnumMap> handlerSet = HANDLERS.get( clz ); + if( this.isInvalid() ) + this.validate(); + } - if ( handlerSet == null ) + @Override + // NOTE: WAS FINAL, changed for Immibis + final public void readFromNBT( NBTTagCompound data ) + { + super.readFromNBT( data ); + + if( data.hasKey( "customName" ) ) + this.customName = data.getString( "customName" ); + else + this.customName = null; + + try { - HANDLERS.put( clz, handlerSet = new EnumMap>( TileEventType.class ) ); - - for (Method m : clz.getMethods()) + if( this.canBeRotated() ) { - TileEvent te = m.getAnnotation( TileEvent.class ); - if ( te != null ) - { - this.addHandler( handlerSet, te.value(), m ); - } + this.forward = ForgeDirection.valueOf( data.getString( "orientation_forward" ) ); + this.up = ForgeDirection.valueOf( data.getString( "orientation_up" ) ); } } + catch( IllegalArgumentException ignored ) + { + } - List list = handlerSet.get( type ); - - if ( list == null ) - handlerSet.put( type, list = new LinkedList() ); - - return list; + for( AETileEventHandler h : this.getHandlerListFor( TileEventType.WORLD_NBT_READ ) ) + { + h.readFromNBT( this, data ); + } } - private void addHandler(EnumMap> handlerSet, TileEventType value, Method m) + @Override + // NOTE: WAS FINAL, changed for Immibis + final public void writeToNBT( NBTTagCompound data ) { - List list = handlerSet.get( value ); + super.writeToNBT( data ); - if ( list == null ) - handlerSet.put( value, list = new ArrayList() ); + if( this.canBeRotated() ) + { + data.setString( "orientation_forward", this.forward.name() ); + data.setString( "orientation_up", this.up.name() ); + } - list.add( new AETileEventHandler( m, value ) ); + if( this.customName != null ) + data.setString( "customName", this.customName ); + + for( AETileEventHandler h : this.getHandlerListFor( TileEventType.WORLD_NBT_WRITE ) ) + h.writeToNBT( this, data ); + } + + @Override + final public void updateEntity() + { + for( AETileEventHandler h : this.getHandlerListFor( TileEventType.TICK ) ) + h.Tick( this ); + } + + @Override + public Packet getDescriptionPacket() + { + NBTTagCompound data = new NBTTagCompound(); + + ByteBuf stream = Unpooled.buffer(); + + try + { + this.writeToStream( stream ); + if( stream.readableBytes() == 0 ) + return null; + } + catch( Throwable t ) + { + AELog.error( t ); + } + + stream.capacity( stream.readableBytes() ); + data.setByteArray( "X", stream.array() ); + return new S35PacketUpdateTileEntity( this.xCoord, this.yCoord, this.zCoord, 64, data ); } @Override @@ -152,109 +195,39 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, return this.hasHandlerFor( TileEventType.TICK ); } - final public void Tick() + protected boolean hasHandlerFor( TileEventType type ) { - + List list = this.getHandlerListFor( type ); + return list != null && !list.isEmpty(); } @Override - final public void updateEntity() + public void onDataPacket( NetworkManager net, S35PacketUpdateTileEntity pkt ) { - for (AETileEventHandler h : this.getHandlerListFor( TileEventType.TICK )) - h.Tick( this ); + // / pkt.actionType + if( pkt.func_148853_f() == 64 ) + { + ByteBuf stream = Unpooled.copiedBuffer( pkt.func_148857_g().getByteArray( "X" ) ); + if( this.readFromStream( stream ) ) + this.markForUpdate(); + } } @Override public void onChunkUnload() { - if ( !this.isInvalid() ) + if( !this.isInvalid() ) this.invalidate(); } - /** - * for dormant chunk cache. - */ - public void onChunkLoad() - { - if ( this.isInvalid() ) - this.validate(); - } - - @Override - // NOTE: WAS FINAL, changed for Immibis - final public void writeToNBT(NBTTagCompound data) - { - super.writeToNBT( data ); - - if ( this.canBeRotated() ) - { - data.setString( "orientation_forward", this.forward.name() ); - data.setString( "orientation_up", this.up.name() ); - } - - if ( this.customName != null ) - data.setString( "customName", this.customName ); - - for (AETileEventHandler h : this.getHandlerListFor( TileEventType.WORLD_NBT_WRITE )) - h.writeToNBT( this, data ); - } - - @Override - // NOTE: WAS FINAL, changed for Immibis - final public void readFromNBT(NBTTagCompound data) - { - super.readFromNBT( data ); - - if ( data.hasKey( "customName" ) ) - this.customName = data.getString( "customName" ); - else - this.customName = null; - - try - { - if ( this.canBeRotated() ) - { - this.forward = ForgeDirection.valueOf( data.getString( "orientation_forward" ) ); - this.up = ForgeDirection.valueOf( data.getString( "orientation_up" ) ); - } - } - catch (IllegalArgumentException ignored) - { - } - - for (AETileEventHandler h : this.getHandlerListFor( TileEventType.WORLD_NBT_READ )) - { - h.readFromNBT( this, data ); - } - } - - final public void writeToStream(ByteBuf data) - { - try - { - if ( this.canBeRotated() ) - { - byte orientation = (byte) ((this.up.ordinal() << 3) | this.forward.ordinal()); - data.writeByte( orientation ); - } - - for (AETileEventHandler h : this.getHandlerListFor( TileEventType.NETWORK_WRITE )) - h.writeToStream( this, data ); - } - catch (Throwable t) - { - AELog.error( t ); - } - } - - final public boolean readFromStream(ByteBuf data) + final public boolean readFromStream( ByteBuf data ) { boolean output = false; try { - if ( this.canBeRotated() ) + if( this.canBeRotated() ) { ForgeDirection old_Forward = this.forward; ForgeDirection old_Up = this.up; @@ -267,15 +240,15 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, } this.renderFragment = 100; - for (AETileEventHandler h : this.getHandlerListFor( TileEventType.NETWORK_READ )) - if ( h.readFromStream( this, data ) ) + for( AETileEventHandler h : this.getHandlerListFor( TileEventType.NETWORK_READ ) ) + if( h.readFromStream( this, data ) ) output = true; - if ( (this.renderFragment & 1) == 1 ) + if( ( this.renderFragment & 1 ) == 1 ) output = true; this.renderFragment = 0; } - catch (Throwable t) + catch( Throwable t ) { AELog.error( t ); } @@ -283,6 +256,40 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, return output; } + public void markForUpdate() + { + if( this.renderFragment > 0 ) + this.renderFragment |= 1; + else + { + // TODO: Optimize Network Load + if( this.worldObj != null ) + { + AELog.blockUpdate( this.xCoord, this.yCoord, this.zCoord, this ); + this.worldObj.markBlockForUpdate( this.xCoord, this.yCoord, this.zCoord ); + } + } + } + + final public void writeToStream( ByteBuf data ) + { + try + { + if( this.canBeRotated() ) + { + byte orientation = (byte) ( ( this.up.ordinal() << 3 ) | this.forward.ordinal() ); + data.writeByte( orientation ); + } + + for( AETileEventHandler h : this.getHandlerListFor( TileEventType.NETWORK_WRITE ) ) + h.writeToStream( this, data ); + } + catch( Throwable t ) + { + AELog.error( t ); + } + } + /** * By default all blocks can have orientation, this handles saving, and loading, as well as synchronization. * @@ -294,6 +301,43 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, return true; } + protected List getHandlerListFor( TileEventType type ) + { + Class clz = this.getClass(); + EnumMap> handlerSet = HANDLERS.get( clz ); + + if( handlerSet == null ) + { + HANDLERS.put( clz, handlerSet = new EnumMap>( TileEventType.class ) ); + + for( Method m : clz.getMethods() ) + { + TileEvent te = m.getAnnotation( TileEvent.class ); + if( te != null ) + { + this.addHandler( handlerSet, te.value(), m ); + } + } + } + + List list = handlerSet.get( type ); + + if( list == null ) + handlerSet.put( type, list = new LinkedList() ); + + return list; + } + + private void addHandler( EnumMap> handlerSet, TileEventType value, Method m ) + { + List list = handlerSet.get( value ); + + if( list == null ) + handlerSet.put( value, list = new ArrayList() ); + + list.add( new AETileEventHandler( m, value ) ); + } + @Override public ForgeDirection getForward() { @@ -307,7 +351,7 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, } @Override - public void setOrientation(ForgeDirection inForward, ForgeDirection inUp) + public void setOrientation( ForgeDirection inForward, ForgeDirection inUp ) { this.forward = inForward; this.up = inUp; @@ -315,60 +359,45 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); } - public void onPlacement(ItemStack stack, EntityPlayer player, int side) + public void onPlacement( ItemStack stack, EntityPlayer player, int side ) { - if ( stack.hasTagCompound() ) + if( stack.hasTagCompound() ) { this.uploadSettings( SettingsFrom.DISMANTLE_ITEM, stack.getTagCompound() ); } } - @Override - public Packet getDescriptionPacket() + /** + * depending on the from, different settings will be accepted, don't call this with null + * + * @param from source of settings + * @param compound compound of source + */ + public void uploadSettings( SettingsFrom from, NBTTagCompound compound ) { - NBTTagCompound data = new NBTTagCompound(); - - ByteBuf stream = Unpooled.buffer(); - - try + if( compound != null && this instanceof IConfigurableObject ) { - this.writeToStream( stream ); - if ( stream.readableBytes() == 0 ) - return null; - } - catch (Throwable t) - { - AELog.error( t ); + IConfigManager cm = ( (IConfigurableObject) this ).getConfigManager(); + if( cm != null ) + cm.readFromNBT( compound ); } - stream.capacity( stream.readableBytes() ); - data.setByteArray( "X", stream.array() ); - return new S35PacketUpdateTileEntity( this.xCoord, this.yCoord, this.zCoord, 64, data ); - } - - @Override - public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) - { - // / pkt.actionType - if ( pkt.func_148853_f() == 64 ) + if( this instanceof IPriorityHost ) { - ByteBuf stream = Unpooled.copiedBuffer( pkt.func_148857_g().getByteArray( "X" ) ); - if ( this.readFromStream( stream ) ) - this.markForUpdate(); + IPriorityHost pHost = (IPriorityHost) this; + pHost.setPriority( compound.getInteger( "priority" ) ); } - } - public void markForUpdate() - { - if ( this.renderFragment > 0 ) - this.renderFragment |= 1; - else + if( this instanceof ISegmentedInventory ) { - // TODO: Optimize Network Load - if ( this.worldObj != null ) + IInventory inv = ( (ISegmentedInventory) this ).getInventoryByName( "config" ); + if( inv instanceof AppEngInternalAEInventory ) { - AELog.blockUpdate( this.xCoord, this.yCoord, this.zCoord, this ); - this.worldObj.markBlockForUpdate( this.xCoord, this.yCoord, this.zCoord ); + AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; + AppEngInternalAEInventory tmp = new AppEngInternalAEInventory( null, target.getSizeInventory() ); + tmp.readFromNBT( compound, "config" ); + for( int x = 0; x < tmp.getSizeInventory(); x++ ) + target.setInventorySlotContents( x, tmp.getStackInSlot( x ) ); } } } @@ -376,30 +405,29 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, /** * returns the contents of the tile entity, into the world, defaults to dropping everything in the inventory. * - * @param w world - * @param x x pos of tile entity - * @param y y pos of tile entity - * @param z z pos of tile entity + * @param w world + * @param x x pos of tile entity + * @param y y pos of tile entity + * @param z z pos of tile entity * @param drops drops of tile entity */ @Override - public void getDrops(World w, int x, int y, int z, ArrayList drops) + public void getDrops( World w, int x, int y, int z, ArrayList drops ) { - if ( this instanceof IInventory ) + if( this instanceof IInventory ) { IInventory inv = (IInventory) this; - for (int l = 0; l < inv.getSizeInventory(); l++) + for( int l = 0; l < inv.getSizeInventory(); l++ ) { ItemStack is = inv.getStackInSlot( l ); - if ( is != null ) + if( is != null ) drops.add( is ); } } - } - public void getNoDrops(World w, int x, int y, int z, ArrayList drops) + public void getNoDrops( World w, int x, int y, int z, ArrayList drops ) { } @@ -409,104 +437,49 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, } - /** - * depending on the from, different settings will be accepted, don't call this with null - * - * @param from source of settings - * @param compound compound of source - */ - public void uploadSettings(SettingsFrom from, NBTTagCompound compound) - { - if ( compound != null && this instanceof IConfigurableObject ) - { - IConfigManager cm = ((IConfigurableObject) this).getConfigManager(); - if ( cm != null ) - cm.readFromNBT( compound ); - } - - if ( this instanceof IPriorityHost ) - { - IPriorityHost pHost = (IPriorityHost) this; - pHost.setPriority( compound.getInteger( "priority" ) ); - } - - if ( this instanceof ISegmentedInventory ) - { - IInventory inv = ((ISegmentedInventory) this).getInventoryByName( "config" ); - if ( inv instanceof AppEngInternalAEInventory ) - { - AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; - AppEngInternalAEInventory tmp = new AppEngInternalAEInventory( null, target.getSizeInventory() ); - tmp.readFromNBT( compound, "config" ); - for (int x = 0; x < tmp.getSizeInventory(); x++) - target.setInventorySlotContents( x, tmp.getStackInSlot( x ) ); - } - } - } - /** * null means nothing to store... * * @param from source of settings + * * @return compound of source */ - public NBTTagCompound downloadSettings(SettingsFrom from) + public NBTTagCompound downloadSettings( SettingsFrom from ) { NBTTagCompound output = new NBTTagCompound(); - if ( this.hasCustomName() ) + if( this.hasCustomName() ) { NBTTagCompound dsp = new NBTTagCompound(); dsp.setString( "Name", this.getCustomName() ); output.setTag( "display", dsp ); } - if ( this instanceof IConfigurableObject ) + if( this instanceof IConfigurableObject ) { - IConfigManager cm = ((IConfigurableObject) this).getConfigManager(); - if ( cm != null ) + IConfigManager cm = ( (IConfigurableObject) this ).getConfigManager(); + if( cm != null ) cm.writeToNBT( output ); } - if ( this instanceof IPriorityHost ) + if( this instanceof IPriorityHost ) { IPriorityHost pHost = (IPriorityHost) this; output.setInteger( "priority", pHost.getPriority() ); } - if ( this instanceof ISegmentedInventory ) + if( this instanceof ISegmentedInventory ) { - IInventory inv = ((ISegmentedInventory) this).getInventoryByName( "config" ); - if ( inv instanceof AppEngInternalAEInventory ) + IInventory inv = ( (ISegmentedInventory) this ).getInventoryByName( "config" ); + if( inv instanceof AppEngInternalAEInventory ) { - ((AppEngInternalAEInventory) inv).writeToNBT( output, "config" ); + ( (AppEngInternalAEInventory) inv ).writeToNBT( output, "config" ); } } return output.hasNoTags() ? null : output; } - public void securityBreak() - { - this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, true ); - this.disableDrops(); - } - - public void saveChanges() - { - super.markDirty(); - } - - public boolean requiresTESR() - { - return false; - } - - public void setName(String name) - { - this.customName = name; - } - @Override public String getCustomName() { @@ -519,4 +492,29 @@ public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, return this.customName != null && this.customName.length() > 0; } + public void securityBreak() + { + this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, true ); + this.disableDrops(); + } + + public void disableDrops() + { + DROP_NO_ITEMS.set( new WeakReference( this ) ); + } + + public void saveChanges() + { + super.markDirty(); + } + + public boolean requiresTESR() + { + return false; + } + + public void setName( String name ) + { + this.customName = name; + } } diff --git a/src/main/java/appeng/tile/TileEvent.java b/src/main/java/appeng/tile/TileEvent.java index eb73c7cce..4e7da2ce2 100644 --- a/src/main/java/appeng/tile/TileEvent.java +++ b/src/main/java/appeng/tile/TileEvent.java @@ -18,14 +18,16 @@ package appeng.tile; + import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import appeng.tile.events.TileEventType; -@Retention(RetentionPolicy.RUNTIME) -public @interface TileEvent { + +@Retention( RetentionPolicy.RUNTIME ) +public @interface TileEvent +{ TileEventType value(); - } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java b/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java index 8f6918e02..3c16e1766 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java @@ -18,6 +18,7 @@ package appeng.tile.crafting; + import java.io.IOException; import io.netty.buffer.ByteBuf; @@ -36,27 +37,28 @@ import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.util.item.AEItemStack; + public class TileCraftingMonitorTile extends TileCraftingTile implements IColorableTile { - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public Integer dspList; - @SideOnly(Side.CLIENT) + @SideOnly( Side.CLIENT ) public boolean updateList; IAEItemStack dspPlay; AEColor paintedColor = AEColor.Transparent; - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileCraftingMonitorTile(ByteBuf data) throws IOException + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileCraftingMonitorTile( ByteBuf data ) throws IOException { AEColor oldPaintedColor = this.paintedColor; this.paintedColor = AEColor.values()[data.readByte()]; boolean hasItem = data.readBoolean(); - if ( hasItem ) + if( hasItem ) this.dspPlay = AEItemStack.loadItemStackFromPacket( data ); else this.dspPlay = null; @@ -65,12 +67,12 @@ public class TileCraftingMonitorTile extends TileCraftingTile implements IColora return oldPaintedColor != this.paintedColor; // tesr! } - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileCraftingMonitorTile(ByteBuf data) throws IOException + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileCraftingMonitorTile( ByteBuf data ) throws IOException { data.writeByte( this.paintedColor.ordinal() ); - if ( this.dspPlay == null ) + if( this.dspPlay == null ) data.writeBoolean( false ); else { @@ -79,15 +81,15 @@ public class TileCraftingMonitorTile extends TileCraftingTile implements IColora } } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileCraftingMonitorTile(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileCraftingMonitorTile( NBTTagCompound data ) { - if ( data.hasKey( "paintedColor" ) ) + if( data.hasKey( "paintedColor" ) ) this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileCraftingMonitorTile(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileCraftingMonitorTile( NBTTagCompound data ) { data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); } @@ -104,16 +106,16 @@ public class TileCraftingMonitorTile extends TileCraftingTile implements IColora return true; } - public void setJob(IAEItemStack is) + public void setJob( IAEItemStack is ) { - if ( (is == null) != (this.dspPlay == null) ) + if( ( is == null ) != ( this.dspPlay == null ) ) { this.dspPlay = is == null ? null : is.copy(); this.markForUpdate(); } - else if ( is != null && this.dspPlay != null ) + else if( is != null && this.dspPlay != null ) { - if ( is.getStackSize() != this.dspPlay.getStackSize() ) + if( is.getStackSize() != this.dspPlay.getStackSize() ) { this.dspPlay = is.copy(); this.markForUpdate(); @@ -139,9 +141,9 @@ public class TileCraftingMonitorTile extends TileCraftingTile implements IColora } @Override - public boolean recolourBlock(ForgeDirection side, AEColor newPaintedColor, EntityPlayer who) + public boolean recolourBlock( ForgeDirection side, AEColor newPaintedColor, EntityPlayer who ) { - if ( this.paintedColor == newPaintedColor ) + if( this.paintedColor == newPaintedColor ) return false; this.paintedColor = newPaintedColor; diff --git a/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java b/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java index a0c258b57..f895ce0d8 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java @@ -18,6 +18,7 @@ package appeng.tile.crafting; + import net.minecraft.item.ItemStack; import appeng.api.AEApi; @@ -29,27 +30,27 @@ public class TileCraftingStorageTile extends TileCraftingTile public static final int KILO_SCALAR = 1024; @Override - protected ItemStack getItemFromTile(Object obj) + protected ItemStack getItemFromTile( Object obj ) { final IBlocks blocks = AEApi.instance().definitions().blocks(); - final int storage = ((TileCraftingTile) obj).getStorageBytes() / KILO_SCALAR; + final int storage = ( (TileCraftingTile) obj ).getStorageBytes() / KILO_SCALAR; - switch ( storage ) + switch( storage ) { case 4: - for ( ItemStack stack : blocks.craftingStorage4k().maybeStack( 1 ).asSet() ) + for( ItemStack stack : blocks.craftingStorage4k().maybeStack( 1 ).asSet() ) { return stack; } break; case 16: - for ( ItemStack stack : blocks.craftingStorage16k().maybeStack( 1 ).asSet() ) + for( ItemStack stack : blocks.craftingStorage16k().maybeStack( 1 ).asSet() ) { return stack; } break; case 64: - for ( ItemStack stack : blocks.craftingStorage64k().maybeStack( 1 ).asSet() ) + for( ItemStack stack : blocks.craftingStorage64k().maybeStack( 1 ).asSet() ) { return stack; } @@ -74,20 +75,20 @@ public class TileCraftingStorageTile extends TileCraftingTile @Override public int getStorageBytes() { - if ( this.worldObj == null || this.notLoaded() ) + if( this.worldObj == null || this.notLoaded() ) return 0; - switch (this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 3) + switch( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 3 ) { - default: - case 0: - return 1024; - case 1: - return 4 * 1024; - case 2: - return 16 * 1024; - case 3: - return 64 * 1024; + default: + case 0: + return 1024; + case 1: + return 4 * 1024; + case 2: + return 16 * 1024; + case 3: + return 64 * 1024; } } } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingTile.java b/src/main/java/appeng/tile/crafting/TileCraftingTile.java index 28c2ba80d..5a691eb9c 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingTile.java @@ -78,9 +78,9 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP @Override protected ItemStack getItemFromTile( Object obj ) { - if ( ( (TileCraftingTile) obj ).isAccelerator() ) + if( ( (TileCraftingTile) obj ).isAccelerator() ) { - for ( ItemStack accelerator : AEApi.instance().definitions().blocks().craftingAccelerator().maybeStack( 1 ).asSet() ) + for( ItemStack accelerator : AEApi.instance().definitions().blocks().craftingAccelerator().maybeStack( 1 ).asSet() ) { return accelerator; } @@ -100,13 +100,13 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP public void setName( String name ) { super.setName( name ); - if ( this.cluster != null ) + if( this.cluster != null ) this.cluster.updateName(); } public boolean isAccelerator() { - if ( this.worldObj == null ) + if( this.worldObj == null ) return false; return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 3 ) == 1; } @@ -126,7 +126,7 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP public void updateStatus( CraftingCPUCluster c ) { - if ( this.cluster != null && this.cluster != c ) + if( this.cluster != null && this.cluster != c ) this.cluster.breakCluster(); this.cluster = c; @@ -135,24 +135,24 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP public void updateMeta( boolean updateFormed ) { - if ( this.worldObj == null || this.notLoaded() ) + if( this.worldObj == null || this.notLoaded() ) return; boolean formed = this.isFormed(); boolean power = false; - if ( this.gridProxy.isReady() ) + if( this.gridProxy.isReady() ) power = this.gridProxy.isActive(); int current = this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ); int newMeta = ( current & 3 ) | ( formed ? 8 : 0 ) | ( power ? 4 : 0 ); - if ( current != newMeta ) + if( current != newMeta ) this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, newMeta, 2 ); - if ( updateFormed ) + if( updateFormed ) { - if ( formed ) + if( formed ) this.gridProxy.setValidSides( EnumSet.allOf( ForgeDirection.class ) ); else this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); @@ -161,7 +161,7 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP public boolean isFormed() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 8 ) == 8; return this.cluster != null; } @@ -170,7 +170,7 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP public void writeToNBT_TileCraftingTile( NBTTagCompound data ) { data.setBoolean( "core", this.isCoreBlock ); - if ( this.isCoreBlock && this.cluster != null ) + if( this.isCoreBlock && this.cluster != null ) this.cluster.writeToNBT( data ); } @@ -178,9 +178,9 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP public void readFromNBT_TileCraftingTile( NBTTagCompound data ) { this.isCoreBlock = data.getBoolean( "core" ); - if ( this.isCoreBlock ) + if( this.isCoreBlock ) { - if ( this.cluster != null ) + if( this.cluster != null ) this.cluster.readFromNBT( data ); else this.previousState = (NBTTagCompound) data.copy(); @@ -190,10 +190,10 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP @Override public void disconnect( boolean update ) { - if ( this.cluster != null ) + if( this.cluster != null ) { this.cluster.destroy(); - if ( update ) + if( update ) this.updateMeta( true ); } } @@ -225,12 +225,6 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP public boolean isStatus() { return false; - } @Override - public boolean isPowered() - { - if ( Platform.isClient() ) - return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 4 ) == 4; - return this.gridProxy.isActive(); } public boolean isStorage() @@ -245,7 +239,7 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP public void breakCluster() { - if ( this.cluster != null ) + if( this.cluster != null ) { this.cluster.cancel(); IMEInventory inv = this.cluster.getInventory(); @@ -253,20 +247,20 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP LinkedList places = new LinkedList(); Iterator i = this.cluster.getTiles(); - while ( i.hasNext() ) + while( i.hasNext() ) { IGridHost h = i.next(); - if ( h == this ) + if( h == this ) places.add( new WorldCoord( this ) ); else { TileEntity te = (TileEntity) h; - for ( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) { WorldCoord wc = new WorldCoord( te ); wc.add( d, 1 ); - if ( this.worldObj.isAirBlock( wc.x, wc.y, wc.z ) ) + if( this.worldObj.isAirBlock( wc.x, wc.y, wc.z ) ) places.add( wc ); } } @@ -274,17 +268,17 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP Collections.shuffle( places ); - if ( places.isEmpty() ) + if( places.isEmpty() ) throw new RuntimeException( "No air or even the tile hat was destroyed?!?!" ); - for ( IAEItemStack ais : inv.getAvailableItems( AEApi.instance().storage().createItemList() ) ) + for( IAEItemStack ais : inv.getAvailableItems( AEApi.instance().storage().createItemList() ) ) { ais = ais.copy(); ais.setStackSize( ais.getItemStack().getMaxStackSize() ); - while ( true ) + while( true ) { IAEItemStack g = inv.extractItems( ais.copy(), Actionable.MODULATE, this.cluster.getActionSource() ); - if ( g == null ) + if( g == null ) break; WorldCoord wc = places.poll(); @@ -298,12 +292,18 @@ public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IP } } - + @Override + public boolean isPowered() + { + if( Platform.isClient() ) + return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 4 ) == 4; + return this.gridProxy.isActive(); + } @Override public boolean isActive() { - if ( Platform.isServer() ) + if( Platform.isServer() ) return this.gridProxy.isActive(); return this.isPowered() && this.isFormed(); } diff --git a/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java b/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java index d68e059f0..8bccd2b90 100644 --- a/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java +++ b/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java @@ -77,8 +77,7 @@ import appeng.util.Platform; import appeng.util.item.AEItemStack; -public class TileMolecularAssembler extends AENetworkInvTile - implements IUpgradeableHost, IConfigManagerHost, IGridTickable, ICraftingMachine, IPowerChannelState +public class TileMolecularAssembler extends AENetworkInvTile implements IUpgradeableHost, IConfigManagerHost, IGridTickable, ICraftingMachine, IPowerChannelState { private static final int[] SIDES = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; @@ -116,19 +115,19 @@ public class TileMolecularAssembler extends AENetworkInvTile @Override public boolean pushPattern( ICraftingPatternDetails patternDetails, InventoryCrafting table, ForgeDirection where ) { - if ( this.myPattern == null ) + if( this.myPattern == null ) { boolean isEmpty = true; - for ( int x = 0; x < this.inv.getSizeInventory(); x++ ) + for( int x = 0; x < this.inv.getSizeInventory(); x++ ) isEmpty = this.inv.getStackInSlot( x ) == null && isEmpty; - if ( isEmpty && patternDetails.isCraftable() ) + if( isEmpty && patternDetails.isCraftable() ) { this.forcePlan = true; this.myPlan = patternDetails; this.pushDirection = where; - for ( int x = 0; x < table.getSizeInventory(); x++ ) + for( int x = 0; x < table.getSizeInventory(); x++ ) this.inv.setInventorySlotContents( x, table.getStackInSlot( x ) ); this.updateSleepiness(); @@ -143,16 +142,16 @@ public class TileMolecularAssembler extends AENetworkInvTile { boolean wasEnabled = this.isAwake; this.isAwake = this.myPlan != null && this.hasMats() || this.canPush(); - if ( wasEnabled != this.isAwake ) + if( wasEnabled != this.isAwake ) { try { - if ( this.isAwake ) + if( this.isAwake ) this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); else this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -166,10 +165,10 @@ public class TileMolecularAssembler extends AENetworkInvTile private boolean hasMats() { - if ( this.myPlan == null ) + if( this.myPlan == null ) return false; - for ( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) + for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) this.craftingInv.setInventorySlotContents( x, this.inv.getStackInSlot( x ) ); return this.myPlan.getOutput( this.craftingInv, this.getWorldObj() ) != null; @@ -204,10 +203,10 @@ public class TileMolecularAssembler extends AENetworkInvTile @TileEvent( TileEventType.WORLD_NBT_WRITE ) public void writeToNBT_TileMolecularAssembler( NBTTagCompound data ) { - if ( this.forcePlan && this.myPlan != null ) + if( this.forcePlan && this.myPlan != null ) { ItemStack pattern = this.myPlan.getPattern(); - if ( pattern != null ) + if( pattern != null ) { NBTTagCompound compound = new NBTTagCompound(); pattern.writeToNBT( compound ); @@ -224,16 +223,16 @@ public class TileMolecularAssembler extends AENetworkInvTile @TileEvent( TileEventType.WORLD_NBT_READ ) public void readFromNBT_TileMolecularAssembler( NBTTagCompound data ) { - if ( data.hasKey( "myPlan" ) ) + if( data.hasKey( "myPlan" ) ) { ItemStack myPat = ItemStack.loadItemStackFromNBT( data.getCompoundTag( "myPlan" ) ); - if ( myPat != null && myPat.getItem() instanceof ItemEncodedPattern ) + if( myPat != null && myPat.getItem() instanceof ItemEncodedPattern ) { World w = this.getWorldObj(); ItemEncodedPattern iep = (ItemEncodedPattern) myPat.getItem(); ICraftingPatternDetails ph = iep.getPatternForItem( myPat, w ); - if ( ph != null && ph.isCraftable() ) + if( ph != null && ph.isCraftable() ) { this.forcePlan = true; this.myPlan = ph; @@ -252,20 +251,20 @@ public class TileMolecularAssembler extends AENetworkInvTile { this.reboot = true; - if ( this.forcePlan ) + if( this.forcePlan ) return; ItemStack is = this.inv.getStackInSlot( 10 ); - if ( is != null && is.getItem() instanceof ItemEncodedPattern ) + if( is != null && is.getItem() instanceof ItemEncodedPattern ) { - if ( !Platform.isSameItem( is, this.myPattern ) ) + if( !Platform.isSameItem( is, this.myPattern ) ) { World w = this.getWorldObj(); ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); - if ( ph != null && ph.isCraftable() ) + if( ph != null && ph.isCraftable() ) { this.progress = 0; this.myPattern = is; @@ -306,10 +305,10 @@ public class TileMolecularAssembler extends AENetworkInvTile @Override public IInventory getInventoryByName( String name ) { - if ( name.equals( "upgrades" ) ) + if( name.equals( "upgrades" ) ) return this.upgrades; - if ( name.equals( "mac" ) ) + if( name.equals( "mac" ) ) return this.inv; return null; @@ -321,6 +320,12 @@ public class TileMolecularAssembler extends AENetworkInvTile } + @Override + public IInventory getInternalInventory() + { + return this.inv; + } + @Override public int getInventoryStackLimit() { @@ -330,10 +335,10 @@ public class TileMolecularAssembler extends AENetworkInvTile @Override public boolean isItemValidForSlot( int i, ItemStack itemstack ) { - if ( i >= 9 ) + if( i >= 9 ) return false; - if ( this.hasPattern() ) + if( this.hasPattern() ) return this.myPlan.isValidItemForSlot( i, itemstack, this.getWorldObj() ); return false; @@ -344,25 +349,19 @@ public class TileMolecularAssembler extends AENetworkInvTile return this.myPlan != null && this.inv.getStackInSlot( 10 ) != null; } - @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side ) - { - return slotIndex == 9; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - @Override public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) { - if ( inv == this.inv ) + if( inv == this.inv ) this.recalculatePlan(); } + @Override + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) + { + return slotIndex == 9; + } + @Override public int[] getAccessibleSlotsBySide( ForgeDirection whichSide ) { @@ -379,10 +378,10 @@ public class TileMolecularAssembler extends AENetworkInvTile { super.getDrops( w, x, y, z, drops ); - for ( int h = 0; h < this.upgrades.getSizeInventory(); h++ ) + for( int h = 0; h < this.upgrades.getSizeInventory(); h++ ) { ItemStack is = this.upgrades.getStackInSlot( h ); - if ( is != null ) + if( is != null ) drops.add( is ); } } @@ -398,12 +397,12 @@ public class TileMolecularAssembler extends AENetworkInvTile @Override public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) { - if ( this.inv.getStackInSlot( 9 ) != null ) + if( this.inv.getStackInSlot( 9 ) != null ) { this.pushOut( this.inv.getStackInSlot( 9 ) ); // did it eject? - if ( this.inv.getStackInSlot( 9 ) == null ) + if( this.inv.getStackInSlot( 9 ) == null ) this.markDirty(); this.ejectHeldItems(); @@ -412,21 +411,21 @@ public class TileMolecularAssembler extends AENetworkInvTile return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; } - if ( this.myPlan == null ) + if( this.myPlan == null ) { this.updateSleepiness(); return TickRateModulation.SLEEP; } - if ( this.reboot ) + if( this.reboot ) TicksSinceLastCall = 1; - if ( !this.isAwake ) + if( !this.isAwake ) return TickRateModulation.SLEEP; this.reboot = false; int speed = 10; - switch ( this.upgrades.getInstalledUpgrades( Upgrades.SPEED ) ) + switch( this.upgrades.getInstalledUpgrades( Upgrades.SPEED ) ) { case 0: this.progress += this.userPower( TicksSinceLastCall, speed = 10, 1.0 ); @@ -448,23 +447,23 @@ public class TileMolecularAssembler extends AENetworkInvTile break; } - if ( this.progress >= 100 ) + if( this.progress >= 100 ) { - for ( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) + for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) this.craftingInv.setInventorySlotContents( x, this.inv.getStackInSlot( x ) ); this.progress = 0; ItemStack output = this.myPlan.getOutput( this.craftingInv, this.getWorldObj() ); - if ( output != null ) + if( output != null ) { FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.getWorldObj() ), output, this.craftingInv ); this.pushOut( output.copy() ); - for ( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) + for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) this.inv.setInventorySlotContents( x, Platform.getContainerItem( this.craftingInv.getStackInSlot( x ) ) ); - if ( this.inv.getStackInSlot( 10 ) == null ) + if( this.inv.getStackInSlot( 10 ) == null ) { this.forcePlan = false; this.myPlan = null; @@ -479,7 +478,7 @@ public class TileMolecularAssembler extends AENetworkInvTile IAEItemStack item = AEItemStack.create( output ); NetworkHandler.instance.sendToAllAround( new PacketAssemblerAnimation( this.xCoord, this.yCoord, this.zCoord, (byte) speed, item ), where ); } - catch ( IOException e ) + catch( IOException e ) { // ;P } @@ -495,14 +494,14 @@ public class TileMolecularAssembler extends AENetworkInvTile private void ejectHeldItems() { - if ( this.inv.getStackInSlot( 9 ) == null ) + if( this.inv.getStackInSlot( 9 ) == null ) { - for ( int x = 0; x < 9; x++ ) + for( int x = 0; x < 9; x++ ) { ItemStack is = this.inv.getStackInSlot( x ); - if ( is != null ) + if( is != null ) { - if ( this.myPlan == null || !this.myPlan.isValidItemForSlot( x, is, this.worldObj ) ) + if( this.myPlan == null || !this.myPlan.isValidItemForSlot( x, is, this.worldObj ) ) { this.inv.setInventorySlotContents( 9, is ); this.inv.setInventorySlotContents( x, null ); @@ -520,7 +519,7 @@ public class TileMolecularAssembler extends AENetworkInvTile { return (int) ( this.gridProxy.getEnergy().extractAEPower( ticksPassed * bonusValue * acceleratorTax, Actionable.MODULATE, PowerMultiplier.CONFIG ) / acceleratorTax ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { return 0; } @@ -528,15 +527,15 @@ public class TileMolecularAssembler extends AENetworkInvTile private void pushOut( ItemStack output ) { - if ( this.pushDirection == ForgeDirection.UNKNOWN ) + if( this.pushDirection == ForgeDirection.UNKNOWN ) { - for ( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) output = this.pushTo( output, d ); } else output = this.pushTo( output, this.pushDirection ); - if ( output == null && this.forcePlan ) + if( output == null && this.forcePlan ) { this.forcePlan = false; this.recalculatePlan(); @@ -547,24 +546,24 @@ public class TileMolecularAssembler extends AENetworkInvTile private ItemStack pushTo( ItemStack output, ForgeDirection d ) { - if ( output == null ) + if( output == null ) return output; TileEntity te = this.getWorldObj().getTileEntity( this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ ); - if ( te == null ) + if( te == null ) return output; InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( te, d.getOpposite() ); - if ( adaptor == null ) + if( adaptor == null ) return output; int size = output.stackSize; output = adaptor.addItems( output ); int newSize = output == null ? 0 : output.stackSize; - if ( size != newSize ) + if( size != newSize ) this.markDirty(); return output; @@ -584,12 +583,12 @@ public class TileMolecularAssembler extends AENetworkInvTile { newState = this.gridProxy.isActive() && this.gridProxy.getEnergy().extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.0001; } - catch ( GridAccessException ignored ) + catch( GridAccessException ignored ) { } - if ( newState != this.isPowered ) + if( newState != this.isPowered ) { this.isPowered = newState; this.markForUpdate(); diff --git a/src/main/java/appeng/tile/events/AETileEventHandler.java b/src/main/java/appeng/tile/events/AETileEventHandler.java index 0bee5c429..abac907ba 100644 --- a/src/main/java/appeng/tile/events/AETileEventHandler.java +++ b/src/main/java/appeng/tile/events/AETileEventHandler.java @@ -49,15 +49,15 @@ public class AETileEventHandler { this.method.invoke( tile ); } - catch ( IllegalAccessException e ) + catch( IllegalAccessException e ) { throw new RuntimeException( e ); } - catch ( IllegalArgumentException e ) + catch( IllegalArgumentException e ) { throw new RuntimeException( e ); } - catch ( InvocationTargetException e ) + catch( InvocationTargetException e ) { throw new RuntimeException( e ); } @@ -70,15 +70,15 @@ public class AETileEventHandler { this.method.invoke( tile, data ); } - catch ( IllegalAccessException e ) + catch( IllegalAccessException e ) { throw new RuntimeException( e ); } - catch ( IllegalArgumentException e ) + catch( IllegalArgumentException e ) { throw new RuntimeException( e ); } - catch ( InvocationTargetException e ) + catch( InvocationTargetException e ) { throw new RuntimeException( e ); } @@ -91,15 +91,15 @@ public class AETileEventHandler { this.method.invoke( tile, data ); } - catch ( IllegalAccessException e ) + catch( IllegalAccessException e ) { throw new RuntimeException( e ); } - catch ( IllegalArgumentException e ) + catch( IllegalArgumentException e ) { throw new RuntimeException( e ); } - catch ( InvocationTargetException e ) + catch( InvocationTargetException e ) { throw new RuntimeException( e ); } @@ -112,25 +112,27 @@ public class AETileEventHandler { this.method.invoke( tile, data ); } - catch ( IllegalAccessException e ) + catch( IllegalAccessException e ) { throw new RuntimeException( e ); } - catch ( IllegalArgumentException e ) + catch( IllegalArgumentException e ) { throw new RuntimeException( e ); } - catch ( InvocationTargetException e ) + catch( InvocationTargetException e ) { throw new RuntimeException( e ); } } // NETWORK + /** * returning true from this method, will update the block's render * * @param data data of stream + * * @return true of method could be invoked */ @SideOnly( Side.CLIENT ) @@ -138,20 +140,19 @@ public class AETileEventHandler { try { - return ( Boolean ) this.method.invoke( tile, data ); + return (Boolean) this.method.invoke( tile, data ); } - catch ( IllegalAccessException e ) + catch( IllegalAccessException e ) { throw new RuntimeException( e ); } - catch ( IllegalArgumentException e ) + catch( IllegalArgumentException e ) { throw new RuntimeException( e ); } - catch ( InvocationTargetException e ) + catch( InvocationTargetException e ) { throw new RuntimeException( e ); } } - } diff --git a/src/main/java/appeng/tile/events/TileEventType.java b/src/main/java/appeng/tile/events/TileEventType.java index f3cc273d1..3b242863a 100644 --- a/src/main/java/appeng/tile/events/TileEventType.java +++ b/src/main/java/appeng/tile/events/TileEventType.java @@ -18,6 +18,7 @@ package appeng.tile.events; + public enum TileEventType { TICK, diff --git a/src/main/java/appeng/tile/grid/AENetworkInvTile.java b/src/main/java/appeng/tile/grid/AENetworkInvTile.java index 87a0fa63b..00871f90d 100644 --- a/src/main/java/appeng/tile/grid/AENetworkInvTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkInvTile.java @@ -18,6 +18,7 @@ package appeng.tile.grid; + import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; @@ -29,23 +30,24 @@ import appeng.tile.AEBaseInvTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; + public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionHost, IGridProxyable { - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_AENetwork(NBTTagCompound data) + protected final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); + + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_AENetwork( NBTTagCompound data ) { this.gridProxy.readFromNBT( data ); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_AENetwork(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_AENetwork( NBTTagCompound data ) { this.gridProxy.writeToNBT( data ); } - protected final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); - @Override public AENetworkProxy getProxy() { @@ -53,16 +55,15 @@ public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionH } @Override - public IGridNode getGridNode(ForgeDirection dir) + public void gridChanged() { - return this.gridProxy.getNode(); + } @Override - public void onReady() + public IGridNode getGridNode( ForgeDirection dir ) { - super.onReady(); - this.gridProxy.onReady(); + return this.gridProxy.getNode(); } @Override @@ -73,10 +74,10 @@ public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionH } @Override - public void validate() + public void onReady() { - super.validate(); - this.gridProxy.validate(); + super.onReady(); + this.gridProxy.onReady(); } @Override @@ -87,9 +88,10 @@ public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionH } @Override - public void gridChanged() + public void validate() { - + super.validate(); + this.gridProxy.validate(); } @Override diff --git a/src/main/java/appeng/tile/grid/AENetworkPowerTile.java b/src/main/java/appeng/tile/grid/AENetworkPowerTile.java index fb0bd2bc8..b5a0a6b32 100644 --- a/src/main/java/appeng/tile/grid/AENetworkPowerTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkPowerTile.java @@ -18,6 +18,7 @@ package appeng.tile.grid; + import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; @@ -31,35 +32,30 @@ import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.tile.powersink.AEBasePoweredTile; + public abstract class AENetworkPowerTile extends AEBasePoweredTile implements IActionHost, IGridProxyable { - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_AENetwork(NBTTagCompound data) + protected final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); + + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_AENetwork( NBTTagCompound data ) { this.gridProxy.readFromNBT( data ); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_AENetwork(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_AENetwork( NBTTagCompound data ) { this.gridProxy.writeToNBT( data ); } - protected final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); - @Override public AENetworkProxy getProxy() { return this.gridProxy; } - @Override - public AECableType getCableConnectionType(ForgeDirection dir) - { - return AECableType.SMART; - } - @Override public DimensionalCoord getLocation() { @@ -67,23 +63,21 @@ public abstract class AENetworkPowerTile extends AEBasePoweredTile implements IA } @Override - public IGridNode getGridNode(ForgeDirection dir) + public void gridChanged() + { + + } + + @Override + public IGridNode getGridNode( ForgeDirection dir ) { return this.gridProxy.getNode(); } @Override - public void onReady() + public AECableType getCableConnectionType( ForgeDirection dir ) { - super.onReady(); - this.gridProxy.onReady(); - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.gridProxy.onChunkUnload(); + return AECableType.SMART; } @Override @@ -101,9 +95,17 @@ public abstract class AENetworkPowerTile extends AEBasePoweredTile implements IA } @Override - public void gridChanged() + public void onChunkUnload() { + super.onChunkUnload(); + this.gridProxy.onChunkUnload(); + } + @Override + public void onReady() + { + super.onReady(); + this.gridProxy.onReady(); } @Override diff --git a/src/main/java/appeng/tile/grid/AENetworkTile.java b/src/main/java/appeng/tile/grid/AENetworkTile.java index 746e8c06e..3dafaaf33 100644 --- a/src/main/java/appeng/tile/grid/AENetworkTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkTile.java @@ -18,6 +18,7 @@ package appeng.tile.grid; + import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; @@ -31,39 +32,39 @@ import appeng.tile.AEBaseTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; + public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxyable { - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_AENetwork(NBTTagCompound data) + final protected AENetworkProxy gridProxy = this.createProxy(); + + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_AENetwork( NBTTagCompound data ) { this.gridProxy.readFromNBT( data ); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_AENetwork(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_AENetwork( NBTTagCompound data ) { this.gridProxy.writeToNBT( data ); } - final protected AENetworkProxy gridProxy = this.createProxy(); - protected AENetworkProxy createProxy() { return new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); } @Override - public IGridNode getGridNode(ForgeDirection dir) + public IGridNode getGridNode( ForgeDirection dir ) { return this.gridProxy.getNode(); } @Override - public void onReady() + public AECableType getCableConnectionType( ForgeDirection dir ) { - super.onReady(); - this.gridProxy.onReady(); + return AECableType.SMART; } @Override @@ -74,10 +75,10 @@ public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxy } @Override - public void validate() + public void onReady() { - super.validate(); - this.gridProxy.validate(); + super.onReady(); + this.gridProxy.onReady(); } @Override @@ -88,21 +89,10 @@ public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxy } @Override - public DimensionalCoord getLocation() + public void validate() { - return new DimensionalCoord( this ); - } - - @Override - public AECableType getCableConnectionType(ForgeDirection dir) - { - return AECableType.SMART; - } - - @Override - public void gridChanged() - { - + super.validate(); + this.gridProxy.validate(); } @Override @@ -111,6 +101,18 @@ public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxy return this.gridProxy; } + @Override + public DimensionalCoord getLocation() + { + return new DimensionalCoord( this ); + } + + @Override + public void gridChanged() + { + + } + @Override public IGridNode getActionableNode() { diff --git a/src/main/java/appeng/tile/grindstone/TileCrank.java b/src/main/java/appeng/tile/grindstone/TileCrank.java index c240f1585..1ca4b57a1 100644 --- a/src/main/java/appeng/tile/grindstone/TileCrank.java +++ b/src/main/java/appeng/tile/grindstone/TileCrank.java @@ -37,6 +37,7 @@ import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.util.Platform; + public class TileCrank extends AEBaseTile implements ICustomCollision { @@ -49,18 +50,18 @@ public class TileCrank extends AEBaseTile implements ICustomCollision public int hits = 0; public int rotation = 0; - @TileEvent(TileEventType.TICK) + @TileEvent( TileEventType.TICK ) public void Tick_TileCrank() { - if ( this.rotation > 0 ) + if( this.rotation > 0 ) { - this.visibleRotation -= 360 / (this.ticksPerRotation); + this.visibleRotation -= 360 / ( this.ticksPerRotation ); this.charge++; - if ( this.charge >= this.ticksPerRotation ) + if( this.charge >= this.ticksPerRotation ) { this.charge -= this.ticksPerRotation; ICrankable g = this.getGrinder(); - if ( g != null ) + if( g != null ) g.applyTurn(); } @@ -68,52 +69,58 @@ public class TileCrank extends AEBaseTile implements ICustomCollision } } - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileCrank(ByteBuf data) + public ICrankable getGrinder() + { + if( Platform.isClient() ) + return null; + + ForgeDirection grinder = this.getUp().getOpposite(); + TileEntity te = this.worldObj.getTileEntity( this.xCoord + grinder.offsetX, this.yCoord + grinder.offsetY, this.zCoord + grinder.offsetZ ); + if( te instanceof ICrankable ) + return (ICrankable) te; + return null; + } + + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileCrank( ByteBuf data ) { this.rotation = data.readInt(); return false; } - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileCrank(ByteBuf data) + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileCrank( ByteBuf data ) { data.writeInt( this.rotation ); } - public ICrankable getGrinder() - { - if ( Platform.isClient() ) - return null; - - ForgeDirection grinder = this.getUp().getOpposite(); - TileEntity te = this.worldObj.getTileEntity( this.xCoord + grinder.offsetX, this.yCoord + grinder.offsetY, this.zCoord + grinder.offsetZ ); - if ( te instanceof ICrankable ) - return (ICrankable) te; - return null; - } - @Override - public void setOrientation(ForgeDirection inForward, ForgeDirection inUp) + public void setOrientation( ForgeDirection inForward, ForgeDirection inUp ) { super.setOrientation( inForward, inUp ); this.getBlockType().onNeighborBlockChange( this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR ); } + @Override + public boolean requiresTESR() + { + return true; + } + /** * return true if this should count towards stats. */ public boolean power() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return false; - if ( this.rotation < 3 ) + if( this.rotation < 3 ) { ICrankable g = this.getGrinder(); - if ( g != null ) + if( g != null ) { - if ( g.canTurn() ) + if( g.canTurn() ) { this.hits = 0; this.rotation += this.ticksPerRotation; @@ -123,7 +130,7 @@ public class TileCrank extends AEBaseTile implements ICustomCollision else { this.hits++; - if ( this.hits > 10 ) + if( this.hits > 10 ) { this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, false ); // worldObj.destroyBlock( xCoord, yCoord, zCoord, false ); @@ -136,7 +143,7 @@ public class TileCrank extends AEBaseTile implements ICustomCollision } @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean isVisual) + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean isVisual ) { double xOff = -0.15 * this.getUp().offsetX; double yOff = -0.15 * this.getUp().offsetY; @@ -145,7 +152,7 @@ public class TileCrank extends AEBaseTile implements ICustomCollision } @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) { double xOff = -0.15 * this.getUp().offsetX; double yOff = -0.15 * this.getUp().offsetY; @@ -153,10 +160,4 @@ public class TileCrank extends AEBaseTile implements ICustomCollision out.add( AxisAlignedBB.getBoundingBox( xOff + 0.15, yOff + 0.15, zOff + 0.15,// ahh xOff + 0.85, yOff + 0.85, zOff + 0.85 ) ); } - - @Override - public boolean requiresTESR() - { - return true; - } } diff --git a/src/main/java/appeng/tile/grindstone/TileGrinder.java b/src/main/java/appeng/tile/grindstone/TileGrinder.java index bfe2caaea..90dfef34a 100644 --- a/src/main/java/appeng/tile/grindstone/TileGrinder.java +++ b/src/main/java/appeng/tile/grindstone/TileGrinder.java @@ -18,6 +18,7 @@ package appeng.tile.grindstone; + import java.util.ArrayList; import java.util.List; @@ -36,56 +37,22 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.inv.WrapperInventoryRange; + public class TileGrinder extends AEBaseInvTile implements ICrankable { - int points; - final int[] inputs = new int[] { 0, 1, 2 }; final int[] sides = new int[] { 0, 1, 2, 3, 4, 5 }; final AppEngInternalInventory inv = new AppEngInternalInventory( this, 7 ); + int points; @Override - public void setOrientation(ForgeDirection inForward, ForgeDirection inUp) + public void setOrientation( ForgeDirection inForward, ForgeDirection inUp ) { super.setOrientation( inForward, inUp ); this.getBlockType().onNeighborBlockChange( this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR ); } - private void addItem(InventoryAdaptor sia, ItemStack output) - { - if ( output == null ) - return; - - ItemStack notAdded = sia.addItems( output ); - if ( notAdded != null ) - { - WorldCoord wc = new WorldCoord( this.xCoord, this.yCoord, this.zCoord ); - - wc.add( this.getForward(), 1 ); - - List out = new ArrayList(); - out.add( notAdded ); - - Platform.spawnDrops( this.worldObj, wc.x, wc.y, wc.z, out ); - } - } - - @Override - public boolean canInsertItem(int slotIndex, ItemStack insertingItem, int side ) - { - if ( AEApi.instance().registries().grinder().getRecipeForInput( insertingItem ) == null ) - return false; - - return slotIndex >= 0 && slotIndex <= 2; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side ) - { - return slotIndex >= 3 && slotIndex <= 5; - } - @Override public IInventory getInternalInventory() { @@ -93,42 +60,57 @@ public class TileGrinder extends AEBaseInvTile implements ICrankable } @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) + { + + } + + @Override + public boolean canInsertItem( int slotIndex, ItemStack insertingItem, int side ) + { + if( AEApi.instance().registries().grinder().getRecipeForInput( insertingItem ) == null ) + return false; + + return slotIndex >= 0 && slotIndex <= 2; + } + + @Override + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) + { + return slotIndex >= 3 && slotIndex <= 5; + } + + @Override + public int[] getAccessibleSlotsBySide( ForgeDirection side ) { return this.sides; } - @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) - { - - } - @Override public boolean canTurn() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return false; - if ( null == this.getStackInSlot( 6 ) ) // Add if there isn't one... + if( null == this.getStackInSlot( 6 ) ) // Add if there isn't one... { IInventory src = new WrapperInventoryRange( this, this.inputs, true ); - for (int x = 0; x < src.getSizeInventory(); x++) + for( int x = 0; x < src.getSizeInventory(); x++ ) { ItemStack item = src.getStackInSlot( x ); - if ( item == null ) + if( item == null ) continue; IGrinderEntry r = AEApi.instance().registries().grinder().getRecipeForInput( item ); - if ( r != null ) + if( r != null ) { - if ( item.stackSize >= r.getInput().stackSize ) + if( item.stackSize >= r.getInput().stackSize ) { item.stackSize -= r.getInput().stackSize; ItemStack ais = item.copy(); ais.stackSize = r.getInput().stackSize; - if ( item.stackSize <= 0 ) + if( item.stackSize <= 0 ) item = null; src.setInventorySlotContents( x, item ); @@ -145,16 +127,16 @@ public class TileGrinder extends AEBaseInvTile implements ICrankable @Override public void applyTurn() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; this.points++; ItemStack processing = this.getStackInSlot( 6 ); IGrinderEntry r = AEApi.instance().registries().grinder().getRecipeForInput( processing ); - if ( r != null ) + if( r != null ) { - if ( r.getEnergyCost() > this.points ) + if( r.getEnergyCost() > this.points ) return; this.points = 0; @@ -162,22 +144,40 @@ public class TileGrinder extends AEBaseInvTile implements ICrankable this.addItem( sia, r.getOutput() ); - float chance = (Platform.getRandomInt() % 2000) / 2000.0f; - if ( chance <= r.getOptionalChance() ) + float chance = ( Platform.getRandomInt() % 2000 ) / 2000.0f; + if( chance <= r.getOptionalChance() ) this.addItem( sia, r.getOptionalOutput() ); - chance = (Platform.getRandomInt() % 2000) / 2000.0f; - if ( chance <= r.getSecondOptionalChance() ) + chance = ( Platform.getRandomInt() % 2000 ) / 2000.0f; + if( chance <= r.getSecondOptionalChance() ) this.addItem( sia, r.getSecondOptionalOutput() ); this.setInventorySlotContents( 6, null ); } } + private void addItem( InventoryAdaptor sia, ItemStack output ) + { + if( output == null ) + return; + + ItemStack notAdded = sia.addItems( output ); + if( notAdded != null ) + { + WorldCoord wc = new WorldCoord( this.xCoord, this.yCoord, this.zCoord ); + + wc.add( this.getForward(), 1 ); + + List out = new ArrayList(); + out.add( notAdded ); + + Platform.spawnDrops( this.worldObj, wc.x, wc.y, wc.z, out ); + } + } + @Override - public boolean canCrankAttach(ForgeDirection directionToCrank) + public boolean canCrankAttach( ForgeDirection directionToCrank ) { return this.getUp() == directionToCrank; } - } diff --git a/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java b/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java index 1c20f368f..5fd1a5d9e 100644 --- a/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java @@ -18,6 +18,7 @@ package appeng.tile.inventory; + import java.util.Iterator; import net.minecraft.entity.player.EntityPlayer; @@ -33,58 +34,118 @@ import appeng.util.item.AEItemStack; import appeng.util.iterators.AEInvIterator; import appeng.util.iterators.InvIterator; + public class AppEngInternalAEInventory implements IInventory, Iterable { protected final IAEAppEngInventory te; + protected final IAEItemStack[] inv; final int size; int maxStack; - protected final IAEItemStack[] inv; - - public boolean isEmpty() + public AppEngInternalAEInventory( IAEAppEngInventory _te, int s ) { - for (int x = 0; x < this.size; x++) - if ( this.getStackInSlot( x ) != null ) - return false; - return true; - } - - public AppEngInternalAEInventory(IAEAppEngInventory _te, int s) { this.te = _te; this.size = s; this.maxStack = 64; this.inv = new IAEItemStack[s]; } - public void setMaxStackSize(int s) + public boolean isEmpty() + { + for( int x = 0; x < this.size; x++ ) + if( this.getStackInSlot( x ) != null ) + return false; + return true; + } + + public void setMaxStackSize( int s ) { this.maxStack = s; } - public IAEItemStack getAEStackInSlot(int var1) + public IAEItemStack getAEStackInSlot( int var1 ) { return this.inv[var1]; } - @Override - public ItemStack getStackInSlot(int var1) + public void writeToNBT( NBTTagCompound data, String name ) { - if ( this.inv[var1] == null ) + NBTTagCompound c = new NBTTagCompound(); + this.writeToNBT( c ); + data.setTag( name, c ); + } + + public void writeToNBT( NBTTagCompound target ) + { + for( int x = 0; x < this.size; x++ ) + { + try + { + NBTTagCompound c = new NBTTagCompound(); + + if( this.inv[x] != null ) + { + this.inv[x].writeToNBT( c ); + } + + target.setTag( "#" + x, c ); + } + catch( Exception ignored ) + { + } + } + } + + public void readFromNBT( NBTTagCompound data, String name ) + { + NBTTagCompound c = data.getCompoundTag( name ); + if( c != null ) + this.readFromNBT( c ); + } + + public void readFromNBT( NBTTagCompound target ) + { + for( int x = 0; x < this.size; x++ ) + { + try + { + NBTTagCompound c = target.getCompoundTag( "#" + x ); + + if( c != null ) + this.inv[x] = AEItemStack.loadItemStackFromNBT( c ); + } + catch( Exception e ) + { + AELog.error( e ); + } + } + } + + @Override + public int getSizeInventory() + { + return this.size; + } + + @Override + public ItemStack getStackInSlot( int var1 ) + { + if( this.inv[var1] == null ) return null; return this.inv[var1].getItemStack(); } @Override - public ItemStack decrStackSize(int slot, int qty) + public ItemStack decrStackSize( int slot, int qty ) { - if ( this.inv[slot] != null ) + if( this.inv[slot] != null ) { ItemStack split = this.getStackInSlot( slot ); ItemStack ns = null; - if ( qty >= split.stackSize ) + if( qty >= split.stackSize ) { ns = this.getStackInSlot( slot ); this.inv[slot] = null; @@ -92,7 +153,7 @@ public class AppEngInternalAEInventory implements IInventory, Iterable newItemStack.stackSize ) + if( oldStack.stackSize > newItemStack.stackSize ) { removed = removed.copy(); removed.stackSize -= newItemStack.stackSize; added = null; } - else if ( oldStack.stackSize < newItemStack.stackSize ) + else if( oldStack.stackSize < newItemStack.stackSize ) { added = added.copy(); added.stackSize -= oldStack.stackSize; @@ -145,12 +206,15 @@ public class AppEngInternalAEInventory implements IInventory, Iterable public boolean isEmpty() { - for (int x = 0; x < this.size; x++) - if ( this.getStackInSlot( x ) != null ) + for( int x = 0; x < this.size; x++ ) + if( this.getStackInSlot( x ) != null ) return false; return true; } @@ -78,12 +78,12 @@ public class AppEngInternalInventory implements IInventory, Iterable @Override public ItemStack decrStackSize( int slot, int qty ) { - if ( this.inv[slot] != null ) + if( this.inv[slot] != null ) { ItemStack split = this.getStackInSlot( slot ); ItemStack ns = null; - if ( qty >= split.stackSize ) + if( qty >= split.stackSize ) { ns = this.inv[slot]; this.inv[slot] = null; @@ -91,7 +91,7 @@ public class AppEngInternalInventory implements IInventory, Iterable else ns = split.splitStack( qty ); - if ( this.te != null && this.eventsEnabled() ) + if( this.te != null && this.eventsEnabled() ) { this.te.onChangeInventory( this, slot, InvOperation.decreaseStackSize, ns, null ); } @@ -120,20 +120,20 @@ public class AppEngInternalInventory implements IInventory, Iterable ItemStack oldStack = this.inv[slot]; this.inv[slot] = newItemStack; - if ( this.te != null && this.eventsEnabled() ) + if( this.te != null && this.eventsEnabled() ) { ItemStack removed = oldStack; ItemStack added = newItemStack; - if ( oldStack != null && newItemStack != null && Platform.isSameItem( oldStack, newItemStack ) ) + if( oldStack != null && newItemStack != null && Platform.isSameItem( oldStack, newItemStack ) ) { - if ( oldStack.stackSize > newItemStack.stackSize ) + if( oldStack.stackSize > newItemStack.stackSize ) { removed = removed.copy(); removed.stackSize -= newItemStack.stackSize; added = null; } - else if ( oldStack.stackSize < newItemStack.stackSize ) + else if( oldStack.stackSize < newItemStack.stackSize ) { added = added.copy(); added.stackSize -= oldStack.stackSize; @@ -172,7 +172,7 @@ public class AppEngInternalInventory implements IInventory, Iterable @Override public void markDirty() { - if ( this.te != null && this.eventsEnabled() ) + if( this.te != null && this.eventsEnabled() ) { this.te.onChangeInventory( this, -1, InvOperation.markDirty, null, null ); } @@ -208,7 +208,7 @@ public class AppEngInternalInventory implements IInventory, Iterable // for guis... public void markDirty( int slotIndex ) { - if ( this.te != null && this.eventsEnabled() ) + if( this.te != null && this.eventsEnabled() ) { this.te.onChangeInventory( this, slotIndex, InvOperation.markDirty, null, null ); } @@ -223,20 +223,20 @@ public class AppEngInternalInventory implements IInventory, Iterable public void writeToNBT( NBTTagCompound target ) { - for ( int x = 0; x < this.size; x++ ) + for( int x = 0; x < this.size; x++ ) { try { NBTTagCompound c = new NBTTagCompound(); - if ( this.inv[x] != null ) + if( this.inv[x] != null ) { this.inv[x].writeToNBT( c ); } target.setTag( "#" + x, c ); } - catch ( Exception ignored ) + catch( Exception ignored ) { } } @@ -245,22 +245,22 @@ public class AppEngInternalInventory implements IInventory, Iterable public void readFromNBT( NBTTagCompound data, String name ) { NBTTagCompound c = data.getCompoundTag( name ); - if ( c != null ) + if( c != null ) this.readFromNBT( c ); } public void readFromNBT( NBTTagCompound target ) { - for ( int x = 0; x < this.size; x++ ) + for( int x = 0; x < this.size; x++ ) { try { NBTTagCompound c = target.getCompoundTag( "#" + x ); - if ( c != null ) + if( c != null ) this.inv[x] = ItemStack.loadItemStackFromNBT( c ); } - catch ( Exception e ) + catch( Exception e ) { AELog.error( e ); } diff --git a/src/main/java/appeng/tile/inventory/AppEngNullInventory.java b/src/main/java/appeng/tile/inventory/AppEngNullInventory.java index b123dcb28..20c766d63 100644 --- a/src/main/java/appeng/tile/inventory/AppEngNullInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngNullInventory.java @@ -18,70 +18,21 @@ package appeng.tile.inventory; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; + public class AppEngNullInventory implements IInventory { - public AppEngNullInventory() { - } - - @Override - public ItemStack getStackInSlot(int var1) - { - return null; - } - - @Override - public ItemStack decrStackSize(int slot, int qty) - { - return null; - } - - @Override - public ItemStack getStackInSlotOnClosing(int var1) - { - return null; - } - - @Override - public void setInventorySlotContents(int slot, ItemStack newItemStack) - { - - } - - @Override - public void markDirty() - { - - } - - @Override - public int getInventoryStackLimit() - { - return 0; - } - - @Override - public boolean isUseableByPlayer(EntityPlayer var1) - { - return false; - } - - @Override - public void openInventory() + public AppEngNullInventory() { } - @Override - public void closeInventory() - { - } - - public void writeToNBT(NBTTagCompound target) + public void writeToNBT( NBTTagCompound target ) { } @@ -91,6 +42,30 @@ public class AppEngNullInventory implements IInventory return 0; } + @Override + public ItemStack getStackInSlot( int var1 ) + { + return null; + } + + @Override + public ItemStack decrStackSize( int slot, int qty ) + { + return null; + } + + @Override + public ItemStack getStackInSlotOnClosing( int var1 ) + { + return null; + } + + @Override + public void setInventorySlotContents( int slot, ItemStack newItemStack ) + { + + } + @Override public String getInventoryName() { @@ -104,9 +79,36 @@ public class AppEngNullInventory implements IInventory } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public int getInventoryStackLimit() + { + return 0; + } + + @Override + public void markDirty() + { + + } + + @Override + public boolean isUseableByPlayer( EntityPlayer var1 ) { return false; } + @Override + public void openInventory() + { + } + + @Override + public void closeInventory() + { + } + + @Override + public boolean isItemValidForSlot( int i, ItemStack itemstack ) + { + return false; + } } diff --git a/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java b/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java index 82d0dedd0..2ca28a386 100644 --- a/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java +++ b/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java @@ -18,14 +18,15 @@ package appeng.tile.inventory; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public interface IAEAppEngInventory { void saveChanges(); - void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack); - + void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ); } diff --git a/src/main/java/appeng/tile/inventory/InvOperation.java b/src/main/java/appeng/tile/inventory/InvOperation.java index d271cd469..aaa9a0165 100644 --- a/src/main/java/appeng/tile/inventory/InvOperation.java +++ b/src/main/java/appeng/tile/inventory/InvOperation.java @@ -18,6 +18,7 @@ package appeng.tile.inventory; + public enum InvOperation { decreaseStackSize, setInventorySlotContents, markDirty diff --git a/src/main/java/appeng/tile/misc/TileCellWorkbench.java b/src/main/java/appeng/tile/misc/TileCellWorkbench.java index a0c9cb519..2541feff9 100644 --- a/src/main/java/appeng/tile/misc/TileCellWorkbench.java +++ b/src/main/java/appeng/tile/misc/TileCellWorkbench.java @@ -18,6 +18,7 @@ package appeng.tile.misc; + import java.util.ArrayList; import net.minecraft.inventory.IInventory; @@ -41,6 +42,7 @@ import appeng.tile.inventory.InvOperation; import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; + public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, IAEAppEngInventory, IConfigManagerHost { @@ -50,21 +52,28 @@ public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, I IInventory cacheUpgrades = null; IInventory cacheConfig = null; + private boolean locked = false; + + public TileCellWorkbench() + { + this.cm.registerSetting( Settings.COPY_MODE, CopyMode.CLEAR_ON_REMOVE ); + this.cell.enableClientEvents = true; + } public IInventory getCellUpgradeInventory() { - if ( this.cacheUpgrades == null ) + if( this.cacheUpgrades == null ) { ICellWorkbenchItem cell = this.getCell(); - if ( cell == null ) + if( cell == null ) return null; ItemStack is = this.cell.getStackInSlot( 0 ); - if ( is == null ) + if( is == null ) return null; IInventory inv = cell.getUpgradesInventory( is ); - if ( inv == null ) + if( inv == null ) return null; return this.cacheUpgrades = inv; @@ -72,72 +81,55 @@ public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, I return this.cacheUpgrades; } - public IInventory getCellConfigInventory() + public ICellWorkbenchItem getCell() { - if ( this.cacheConfig == null ) - { - ICellWorkbenchItem cell = this.getCell(); - if ( cell == null ) - return null; + if( this.cell.getStackInSlot( 0 ) == null ) + return null; - ItemStack is = this.cell.getStackInSlot( 0 ); - if ( is == null ) - return null; + if( this.cell.getStackInSlot( 0 ).getItem() instanceof ICellWorkbenchItem ) + return ( (ICellWorkbenchItem) this.cell.getStackInSlot( 0 ).getItem() ); - IInventory inv = cell.getConfigInventory( is ); - if ( inv == null ) - return null; - - return this.cacheConfig = inv; - } - return this.cacheConfig; + return null; } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileCellWorkbench(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileCellWorkbench( NBTTagCompound data ) { this.cell.writeToNBT( data, "cell" ); this.config.writeToNBT( data, "config" ); this.cm.writeToNBT( data ); } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileCellWorkbench(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileCellWorkbench( NBTTagCompound data ) { this.cell.readFromNBT( data, "cell" ); this.config.readFromNBT( data, "config" ); this.cm.readFromNBT( data ); } - public TileCellWorkbench() { - this.cm.registerSetting( Settings.COPY_MODE, CopyMode.CLEAR_ON_REMOVE ); - this.cell.enableClientEvents = true; - } - @Override - public IInventory getInventoryByName(String name) + public IInventory getInventoryByName( String name ) { - if ( name.equals( "config" ) ) + if( name.equals( "config" ) ) return this.config; - if ( name.equals( "cell" ) ) + if( name.equals( "cell" ) ) return this.cell; return null; } @Override - public int getInstalledUpgrades(Upgrades u) + public int getInstalledUpgrades( Upgrades u ) { return 0; } - private boolean locked = false; - @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) { - if ( inv == this.cell && !this.locked ) + if( inv == this.cell && !this.locked ) { this.locked = true; @@ -145,34 +137,34 @@ public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, I this.cacheConfig = null; IInventory c = this.getCellConfigInventory(); - if ( c != null ) + if( c != null ) { boolean cellHasConfig = false; - for (int x = 0; x < c.getSizeInventory(); x++) + for( int x = 0; x < c.getSizeInventory(); x++ ) { - if ( c.getStackInSlot( x ) != null ) + if( c.getStackInSlot( x ) != null ) { cellHasConfig = true; break; } } - if ( cellHasConfig ) + if( cellHasConfig ) { - for (int x = 0; x < this.config.getSizeInventory(); x++) + for( int x = 0; x < this.config.getSizeInventory(); x++ ) this.config.setInventorySlotContents( x, c.getStackInSlot( x ) ); } else { - for (int x = 0; x < this.config.getSizeInventory(); x++) + for( int x = 0; x < this.config.getSizeInventory(); x++ ) c.setInventorySlotContents( x, this.config.getStackInSlot( x ) ); c.markDirty(); } } - else if ( this.cm.getSetting( Settings.COPY_MODE ) == CopyMode.CLEAR_ON_REMOVE ) + else if( this.cm.getSetting( Settings.COPY_MODE ) == CopyMode.CLEAR_ON_REMOVE ) { - for (int x = 0; x < this.config.getSizeInventory(); x++) + for( int x = 0; x < this.config.getSizeInventory(); x++ ) this.config.setInventorySlotContents( x, null ); this.markDirty(); @@ -180,12 +172,12 @@ public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, I this.locked = false; } - else if ( inv == this.config && !this.locked ) + else if( inv == this.config && !this.locked ) { IInventory c = this.getCellConfigInventory(); - if ( c != null ) + if( c != null ) { - for (int x = 0; x < this.config.getSizeInventory(); x++) + for( int x = 0; x < this.config.getSizeInventory(); x++ ) c.setInventorySlotContents( x, this.config.getStackInSlot( x ) ); c.markDirty(); @@ -193,26 +185,36 @@ public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, I } } + public IInventory getCellConfigInventory() + { + if( this.cacheConfig == null ) + { + ICellWorkbenchItem cell = this.getCell(); + if( cell == null ) + return null; + + ItemStack is = this.cell.getStackInSlot( 0 ); + if( is == null ) + return null; + + IInventory inv = cell.getConfigInventory( is ); + if( inv == null ) + return null; + + return this.cacheConfig = inv; + } + return this.cacheConfig; + } + @Override - public void getDrops(World w, int x, int y, int z, ArrayList drops) + public void getDrops( World w, int x, int y, int z, ArrayList drops ) { super.getDrops( w, x, y, z, drops ); - if ( this.cell.getStackInSlot( 0 ) != null ) + if( this.cell.getStackInSlot( 0 ) != null ) drops.add( this.cell.getStackInSlot( 0 ) ); } - public ICellWorkbenchItem getCell() - { - if ( this.cell.getStackInSlot( 0 ) == null ) - return null; - - if ( this.cell.getStackInSlot( 0 ).getItem() instanceof ICellWorkbenchItem ) - return ((ICellWorkbenchItem) this.cell.getStackInSlot( 0 ).getItem()); - - return null; - } - @Override public IConfigManager getConfigManager() { @@ -220,9 +222,8 @@ public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, I } @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { // nothing here.. } - } diff --git a/src/main/java/appeng/tile/misc/TileCharger.java b/src/main/java/appeng/tile/misc/TileCharger.java index 57e146124..b2b591ccf 100644 --- a/src/main/java/appeng/tile/misc/TileCharger.java +++ b/src/main/java/appeng/tile/misc/TileCharger.java @@ -18,6 +18,7 @@ package appeng.tile.misc; + import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; @@ -50,6 +51,7 @@ import appeng.tile.inventory.InvOperation; import appeng.util.Platform; import appeng.util.item.AEItemStack; + public class TileCharger extends AENetworkPowerTile implements ICrankable { @@ -60,14 +62,22 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable int lastUpdate = 0; boolean requiresUpdate = false; + public TileCharger() + { + this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); + this.gridProxy.setFlags(); + this.internalMaxPower = 1500; + this.gridProxy.setIdlePowerUsage( 0 ); + } + @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.COVERED; } - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileCharger(ByteBuf data) + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileCharger( ByteBuf data ) { try { @@ -75,25 +85,25 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable ItemStack is = item.getItemStack(); this.inv.setInventorySlotContents( 0, is ); } - catch (Throwable t) + catch( Throwable t ) { this.inv.setInventorySlotContents( 0, null ); } return false; // TESR doesn't need updates! } - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileCharger(ByteBuf data) throws IOException + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileCharger( ByteBuf data ) throws IOException { AEItemStack is = AEItemStack.create( this.getStackInSlot( 0 ) ); - if ( is != null ) + if( is != null ) is.writeToPacket( data ); } - @TileEvent(TileEventType.TICK) + @TileEvent( TileEventType.TICK ) public void Tick_TileCharger() { - if ( this.lastUpdate > 60 && this.requiresUpdate ) + if( this.lastUpdate > 60 && this.requiresUpdate ) { this.requiresUpdate = false; this.markForUpdate(); @@ -102,53 +112,52 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable this.lastUpdate++; this.tickTickTimer++; - if ( this.tickTickTimer < 20 ) + if( this.tickTickTimer < 20 ) return; this.tickTickTimer = 0; ItemStack myItem = this.getStackInSlot( 0 ); // charge from the network! - if ( this.internalCurrentPower < 1499 ) + if( this.internalCurrentPower < 1499 ) { try { - this.injectExternalPower( PowerUnits.AE, - this.gridProxy.getEnergy().extractAEPower( Math.min( 150.0, 1500.0 - this.internalCurrentPower ), Actionable.MODULATE, PowerMultiplier.ONE ) ); + this.injectExternalPower( PowerUnits.AE, this.gridProxy.getEnergy().extractAEPower( Math.min( 150.0, 1500.0 - this.internalCurrentPower ), Actionable.MODULATE, PowerMultiplier.ONE ) ); this.tickTickTimer = 20; // keep ticking... } - catch (GridAccessException e) + catch( GridAccessException e ) { // continue! } } - if ( myItem == null ) + if( myItem == null ) return; final IMaterials materials = AEApi.instance().definitions().materials(); - if ( this.internalCurrentPower > 149 && Platform.isChargeable( myItem ) ) + if( this.internalCurrentPower > 149 && Platform.isChargeable( myItem ) ) { IAEItemPowerStorage ps = (IAEItemPowerStorage) myItem.getItem(); - if ( ps.getAEMaxPower( myItem ) > ps.getAECurrentPower( myItem ) ) + if( ps.getAEMaxPower( myItem ) > ps.getAECurrentPower( myItem ) ) { double oldPower = this.internalCurrentPower; double adjustment = ps.injectAEPower( myItem, this.extractAEPower( 150.0, Actionable.MODULATE, PowerMultiplier.CONFIG ) ); this.internalCurrentPower += adjustment; - if ( oldPower > this.internalCurrentPower ) + if( oldPower > this.internalCurrentPower ) this.requiresUpdate = true; this.tickTickTimer = 20; // keep ticking... } } - else if ( this.internalCurrentPower > 1499 && materials.certusQuartzCrystal().isSameAs( myItem ) ) + else if( this.internalCurrentPower > 1499 && materials.certusQuartzCrystal().isSameAs( myItem ) ) { - if ( Platform.getRandomFloat() > 0.8f ) // simulate wait + if( Platform.getRandomFloat() > 0.8f ) // simulate wait { this.extractAEPower( this.internalMaxPower, Actionable.MODULATE, PowerMultiplier.CONFIG );// 1500 - for ( ItemStack charged : materials.certusQuartzCrystalCharged().maybeStack( myItem.stackSize ).asSet() ) + for( ItemStack charged : materials.certusQuartzCrystalCharged().maybeStack( myItem.stackSize ).asSet() ) { this.setInventorySlotContents( 0, charged ); } @@ -156,21 +165,20 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable } } - public TileCharger() { - this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.gridProxy.setFlags(); - this.internalMaxPower = 1500; - this.gridProxy.setIdlePowerUsage( 0 ); - } - @Override - public void setOrientation(ForgeDirection inForward, ForgeDirection inUp) + public void setOrientation( ForgeDirection inForward, ForgeDirection inUp ) { super.setOrientation( inForward, inUp ); this.gridProxy.setValidSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); this.setPowerSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); } + @Override + public boolean requiresTESR() + { + return true; + } + @Override public boolean canTurn() { @@ -183,15 +191,15 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable this.injectExternalPower( PowerUnits.AE, 150 ); ItemStack myItem = this.getStackInSlot( 0 ); - if ( this.internalCurrentPower > 1499 ) + if( this.internalCurrentPower > 1499 ) { final IMaterials materials = AEApi.instance().definitions().materials(); - if ( materials.certusQuartzCrystal().isSameAs( myItem ) ) + if( materials.certusQuartzCrystal().isSameAs( myItem ) ) { this.extractAEPower( this.internalMaxPower, Actionable.MODULATE, PowerMultiplier.CONFIG );// 1500 - for ( ItemStack charged : materials.certusQuartzCrystalCharged().maybeStack( myItem.stackSize ).asSet() ) + for( ItemStack charged : materials.certusQuartzCrystalCharged().maybeStack( myItem.stackSize ).asSet() ) { this.setInventorySlotContents( 0, charged ); } @@ -200,7 +208,7 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable } @Override - public boolean canCrankAttach(ForgeDirection directionToCrank) + public boolean canCrankAttach( ForgeDirection directionToCrank ) { return this.getUp() == directionToCrank || this.getUp().getOpposite() == directionToCrank; } @@ -211,18 +219,6 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable return this.inv; } - @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) - { - this.markForUpdate(); - } - - @Override - public int[] getAccessibleSlotsBySide(ForgeDirection whichSide) - { - return this.sides; - } - @Override public int getInventoryStackLimit() { @@ -230,7 +226,7 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { final IItemDefinition cert = AEApi.instance().definitions().materials().certusQuartzCrystal(); @@ -238,29 +234,41 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable } @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side ) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) { - if ( Platform.isChargeable( extractedItem ) ) + this.markForUpdate(); + } + + @Override + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) + { + if( Platform.isChargeable( extractedItem ) ) { IAEItemPowerStorage ips = (IAEItemPowerStorage) extractedItem.getItem(); - if ( ips.getAECurrentPower( extractedItem ) >= ips.getAEMaxPower( extractedItem ) ) + if( ips.getAECurrentPower( extractedItem ) >= ips.getAEMaxPower( extractedItem ) ) return true; } return AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( extractedItem ); } - public void activate(EntityPlayer player) + @Override + public int[] getAccessibleSlotsBySide( ForgeDirection whichSide ) { - if ( !Platform.hasPermissions( new DimensionalCoord( this ), player ) ) + return this.sides; + } + + public void activate( EntityPlayer player ) + { + if( !Platform.hasPermissions( new DimensionalCoord( this ), player ) ) return; ItemStack myItem = this.getStackInSlot( 0 ); - if ( myItem == null ) + if( myItem == null ) { ItemStack held = player.inventory.getCurrentItem(); - if ( AEApi.instance().definitions().materials().certusQuartzCrystal().isSameAs( held ) || Platform.isChargeable( held ) ) + if( AEApi.instance().definitions().materials().certusQuartzCrystal().isSameAs( held ) || Platform.isChargeable( held ) ) { held = player.inventory.decrStackSize( player.inventory.currentItem, 1 ); this.setInventorySlotContents( 0, held ); @@ -274,11 +282,4 @@ public class TileCharger extends AENetworkPowerTile implements ICrankable Platform.spawnDrops( this.worldObj, this.xCoord + this.getForward().offsetX, this.yCoord + this.getForward().offsetY, this.zCoord + this.getForward().offsetZ, drops ); } } - - @Override - public boolean requiresTESR() - { - return true; - } - } diff --git a/src/main/java/appeng/tile/misc/TileCondenser.java b/src/main/java/appeng/tile/misc/TileCondenser.java index 661386416..e521904a7 100644 --- a/src/main/java/appeng/tile/misc/TileCondenser.java +++ b/src/main/java/appeng/tile/misc/TileCondenser.java @@ -18,6 +18,7 @@ package appeng.tile.misc; + import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -43,59 +44,61 @@ import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; + public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConfigManagerHost, IConfigurableObject { - final int[] sides = new int[] { 0, 1 }; static private final FluidTankInfo[] EMPTY = new FluidTankInfo[] { new FluidTankInfo( null, 10 ) }; + final int[] sides = new int[] { 0, 1 }; final AppEngInternalInventory inv = new AppEngInternalInventory( this, 3 ); final ConfigManager cm = new ConfigManager( this ); public double storedPower = 0; - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileCondenser(NBTTagCompound data) + public TileCondenser() + { + this.cm.registerSetting( Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH ); + } + + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileCondenser( NBTTagCompound data ) { this.cm.writeToNBT( data ); data.setDouble( "storedPower", this.storedPower ); } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileCondenser(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileCondenser( NBTTagCompound data ) { this.cm.readFromNBT( data ); this.storedPower = data.getDouble( "storedPower" ); } - public TileCondenser() { - this.cm.registerSetting( Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH ); - } - public double getStorage() { ItemStack is = this.inv.getStackInSlot( 2 ); - if ( is != null ) + if( is != null ) { - if ( is.getItem() instanceof IStorageComponent ) + if( is.getItem() instanceof IStorageComponent ) { IStorageComponent sc = (IStorageComponent) is.getItem(); - if ( sc.isStorageComponent( is ) ) + if( sc.isStorageComponent( is ) ) return sc.getBytes( is ) * 8; } } return 0; } - public void addPower(double rawPower) + public void addPower( double rawPower ) { this.storedPower += rawPower; this.storedPower = Math.max( 0.0, Math.min( this.getStorage(), this.storedPower ) ); double requiredPower = this.getRequiredPower(); ItemStack output = this.getOutput(); - while (requiredPower <= this.storedPower && output != null && requiredPower > 0) + while( requiredPower <= this.storedPower && output != null && requiredPower > 0 ) { - if ( this.canAddOutput( output ) ) + if( this.canAddOutput( output ) ) { this.storedPower -= requiredPower; this.addOutput( output ); @@ -105,10 +108,10 @@ public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConf } } - private boolean canAddOutput(ItemStack output) + private boolean canAddOutput( ItemStack output ) { ItemStack outputStack = this.getStackInSlot( 1 ); - return outputStack == null || (Platform.isSameItem( outputStack, output ) && outputStack.stackSize < outputStack.getMaxStackSize()); + return outputStack == null || ( Platform.isSameItem( outputStack, output ) && outputStack.stackSize < outputStack.getMaxStackSize() ); } /** @@ -116,10 +119,10 @@ public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConf * * @param output to be added output */ - private void addOutput(ItemStack output) + private void addOutput( ItemStack output ) { ItemStack outputStack = this.getStackInSlot( 1 ); - if ( outputStack == null ) + if( outputStack == null ) this.setInventorySlotContents( 1, output.copy() ); else { @@ -132,16 +135,16 @@ public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConf { final IMaterials materials = AEApi.instance().definitions().materials(); - switch ((CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT )) + switch( (CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT ) ) { case MATTER_BALLS: - for ( ItemStack matterBallStack : materials.matterBall().maybeStack( 1 ).asSet() ) + for( ItemStack matterBallStack : materials.matterBall().maybeStack( 1 ).asSet() ) { return matterBallStack; } case SINGULARITY: - for ( ItemStack singularityStack : materials.singularity().maybeStack( 1 ).asSet() ) + for( ItemStack singularityStack : materials.singularity().maybeStack( 1 ).asSet() ) { return singularityStack; } @@ -154,45 +157,7 @@ public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConf public double getRequiredPower() { - return ((CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT )).requiredPower; - } - - @Override - public void setInventorySlotContents(int i, ItemStack itemstack) - { - if ( i == 0 ) - { - if ( itemstack != null ) - this.addPower( itemstack.stackSize ); - } - else - { - this.inv.setInventorySlotContents( 1, itemstack ); - } - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) - { - return i == 0; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side ) - { - return slotIndex != 0; - } - - @Override - public boolean canInsertItem(int slotIndex, ItemStack insertingItem, int side ) - { - return slotIndex == 0; - } - - @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) - { - return this.sides; + return ( (CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT ) ).requiredPower; } @Override @@ -202,12 +167,32 @@ public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConf } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) + public void setInventorySlotContents( int i, ItemStack itemstack ) { - if ( slot == 0 ) + if( i == 0 ) + { + if( itemstack != null ) + this.addPower( itemstack.stackSize ); + } + else + { + this.inv.setInventorySlotContents( 1, itemstack ); + } + } + + @Override + public boolean isItemValidForSlot( int i, ItemStack itemstack ) + { + return i == 0; + } + + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) + { + if( slot == 0 ) { ItemStack is = inv.getStackInSlot( 0 ); - if ( is != null ) + if( is != null ) { this.addPower( is.stackSize ); inv.setInventorySlotContents( 0, null ); @@ -216,46 +201,64 @@ public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConf } @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) + public boolean canInsertItem( int slotIndex, ItemStack insertingItem, int side ) { - if ( doFill ) - this.addPower( (resource == null ? 0.0 : (double) resource.amount) / 500.0 ); + return slotIndex == 0; + } + + @Override + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) + { + return slotIndex != 0; + } + + @Override + public int[] getAccessibleSlotsBySide( ForgeDirection side ) + { + return this.sides; + } + + @Override + public int fill( ForgeDirection from, FluidStack resource, boolean doFill ) + { + if( doFill ) + this.addPower( ( resource == null ? 0.0 : (double) resource.amount ) / 500.0 ); return resource == null ? 0 : resource.amount; } @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) + public FluidStack drain( ForgeDirection from, FluidStack resource, boolean doDrain ) { return null; } @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) + public FluidStack drain( ForgeDirection from, int maxDrain, boolean doDrain ) { return null; } @Override - public boolean canFill(ForgeDirection from, Fluid fluid) + public boolean canFill( ForgeDirection from, Fluid fluid ) { return true; } @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) + public boolean canDrain( ForgeDirection from, Fluid fluid ) { return false; } @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) + public FluidTankInfo[] getTankInfo( ForgeDirection from ) { return EMPTY; } @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { this.addPower( 0 ); } @@ -265,5 +268,4 @@ public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConf { return this.cm; } - } diff --git a/src/main/java/appeng/tile/misc/TileInscriber.java b/src/main/java/appeng/tile/misc/TileInscriber.java index f5ba6cbcf..7ad3a48a6 100644 --- a/src/main/java/appeng/tile/misc/TileInscriber.java +++ b/src/main/java/appeng/tile/misc/TileInscriber.java @@ -129,15 +129,15 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, boolean oldSmash = this.smash; boolean newSmash = ( slot & 64 ) == 64; - if ( oldSmash != newSmash && newSmash ) + if( oldSmash != newSmash && newSmash ) { this.smash = true; this.clientStart = System.currentTimeMillis(); } - for ( int num = 0; num < this.inv.getSizeInventory(); num++ ) + for( int num = 0; num < this.inv.getSizeInventory(); num++ ) { - if ( ( slot & ( 1 << num ) ) > 0 ) + if( ( slot & ( 1 << num ) ) > 0 ) this.inv.setInventorySlotContents( num, AEItemStack.loadItemStackFromPacket( data ).getItemStack() ); else this.inv.setInventorySlotContents( num, null ); @@ -151,16 +151,16 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, { int slot = this.smash ? 64 : 0; - for ( int num = 0; num < this.inv.getSizeInventory(); num++ ) + for( int num = 0; num < this.inv.getSizeInventory(); num++ ) { - if ( this.inv.getStackInSlot( num ) != null ) + if( this.inv.getStackInSlot( num ) != null ) slot |= ( 1 << num ); } data.writeByte( slot ); - for ( int num = 0; num < this.inv.getSizeInventory(); num++ ) + for( int num = 0; num < this.inv.getSizeInventory(); num++ ) { - if ( ( slot & ( 1 << num ) ) > 0 ) + if( ( slot & ( 1 << num ) ) > 0 ) { AEItemStack st = AEItemStack.create( this.inv.getStackInSlot( num ) ); st.writeToPacket( data ); @@ -181,10 +181,10 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, { super.getDrops( w, x, y, z, drops ); - for ( int h = 0; h < this.upgrades.getSizeInventory(); h++ ) + for( int h = 0; h < this.upgrades.getSizeInventory(); h++ ) { ItemStack is = this.upgrades.getStackInSlot( h ); - if ( is != null ) + if( is != null ) drops.add( is ); } } @@ -195,6 +195,12 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, return true; } + @Override + public IInventory getInternalInventory() + { + return this.inv; + } + @Override public int getInventoryStackLimit() { @@ -204,68 +210,62 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, @Override public boolean isItemValidForSlot( int i, ItemStack itemstack ) { - if ( this.smash ) + if( this.smash ) return false; - if ( i == 0 || i == 1 ) + if( i == 0 || i == 1 ) { - if ( AEApi.instance().definitions().materials().namePress().isSameAs( itemstack ) ) + if( AEApi.instance().definitions().materials().namePress().isSameAs( itemstack ) ) { return true; } - for ( ItemStack s : Inscribe.PLATES ) - if ( Platform.isSameItemPrecise( s, itemstack ) ) + for( ItemStack s : Inscribe.PLATES ) + if( Platform.isSameItemPrecise( s, itemstack ) ) return true; } return i == 2; } - @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side ) - { - if ( this.smash ) - return false; - - return slotIndex == 0 || slotIndex == 1 || slotIndex == 3; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - @Override public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) { try { - if ( mc != InvOperation.markDirty ) + if( mc != InvOperation.markDirty ) { - if ( slot != 3 ) + if( slot != 3 ) this.processingTime = 0; - if ( !this.smash ) + if( !this.smash ) this.markForUpdate(); this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } } + @Override + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) + { + if( this.smash ) + return false; + + return slotIndex == 0 || slotIndex == 1 || slotIndex == 3; + } + @Override public int[] getAccessibleSlotsBySide( ForgeDirection d ) { - if ( d == ForgeDirection.UP ) + if( d == ForgeDirection.UP ) return this.top; - if ( d == ForgeDirection.DOWN ) + if( d == ForgeDirection.DOWN ) return this.bottom; return this.sides; @@ -279,7 +279,7 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, private boolean hasWork() { - if ( this.getTask() != null ) + if( this.getTask() != null ) return true; this.processingTime = 0; @@ -292,35 +292,35 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, ItemStack plateB = this.getStackInSlot( 1 ); ItemStack renamedItem = this.getStackInSlot( 2 ); - if ( plateA != null && plateA.stackSize > 1 ) + if( plateA != null && plateA.stackSize > 1 ) return null; - if ( plateB != null && plateB.stackSize > 1 ) + if( plateB != null && plateB.stackSize > 1 ) return null; - if ( renamedItem != null && renamedItem.stackSize > 1 ) + if( renamedItem != null && renamedItem.stackSize > 1 ) return null; final IComparableDefinition namePress = AEApi.instance().definitions().materials().namePress(); boolean isNameA = namePress.isSameAs( plateA ); boolean isNameB = namePress.isSameAs( plateB ); - if ( ( isNameA || isNameB ) && ( isNameA || plateA == null ) && ( isNameB || plateB == null ) ) + if( ( isNameA || isNameB ) && ( isNameA || plateA == null ) && ( isNameB || plateB == null ) ) { - if ( renamedItem != null ) + if( renamedItem != null ) { String name = ""; - if ( plateA != null ) + if( plateA != null ) { NBTTagCompound tag = Platform.openNbtData( plateA ); name += tag.getString( "InscribeName" ); } - if ( plateB != null ) + if( plateB != null ) { NBTTagCompound tag = Platform.openNbtData( plateB ); - if ( name.length() > 0 ) + if( name.length() > 0 ) name += " "; name += tag.getString( "InscribeName" ); } @@ -332,7 +332,7 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, NBTTagCompound display = tag.getCompoundTag( "display" ); tag.setTag( "display", display ); - if ( name.length() > 0 ) + if( name.length() > 0 ) display.setString( "Name", name ); else display.removeTag( "Name" ); @@ -341,7 +341,7 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, } } - for ( InscriberRecipe i : Inscribe.RECIPES ) + for( InscriberRecipe i : Inscribe.RECIPES ) { boolean matchA = ( plateA == null && i.plateA == null ) || ( Platform.isSameItemPrecise( plateA, i.plateA ) ) && // and... @@ -350,11 +350,11 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, boolean matchB = ( plateB == null && i.plateA == null ) || ( Platform.isSameItemPrecise( plateB, i.plateA ) ) && // and... ( plateA == null && i.plateB == null ) | ( Platform.isSameItemPrecise( plateA, i.plateB ) ); - if ( matchA || matchB ) + if( matchA || matchB ) { - for ( ItemStack option : i.imprintable ) + for( ItemStack option : i.imprintable ) { - if ( Platform.isSameItemPrecise( option, this.getStackInSlot( 2 ) ) ) + if( Platform.isSameItemPrecise( option, this.getStackInSlot( 2 ) ) ) return i; } } @@ -365,23 +365,23 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, @Override public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) { - if ( this.smash ) + if( this.smash ) { this.finalStep++; - if ( this.finalStep == 8 ) + if( this.finalStep == 8 ) { InscriberRecipe out = this.getTask(); - if ( out != null ) + if( out != null ) { ItemStack is = out.output.copy(); InventoryAdaptor ad = InventoryAdaptor.getAdaptor( new WrapperInventoryRange( this.inv, 3, 1, true ), ForgeDirection.UNKNOWN ); - if ( ad.addItems( is ) == null ) + if( ad.addItems( is ) == null ) { this.processingTime = 0; - if ( out.usePlates ) + if( out.usePlates ) { this.setInventorySlotContents( 0, null ); this.setInventorySlotContents( 1, null ); @@ -392,7 +392,7 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, this.markDirty(); } - else if ( this.finalStep == 16 ) + else if( this.finalStep == 16 ) { this.finalStep = 0; this.smash = false; @@ -413,36 +413,36 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, double powerThreshold = powerConsumption - 0.01; double powerReq = this.extractAEPower( powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - if ( powerReq <= powerThreshold ) + if( powerReq <= powerThreshold ) { src = eg; powerReq = eg.extractAEPower( powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG ); } - if ( powerReq > powerThreshold ) + if( powerReq > powerThreshold ) { src.extractAEPower( powerConsumption, Actionable.MODULATE, PowerMultiplier.CONFIG ); - if ( this.processingTime == 0 ) + if( this.processingTime == 0 ) this.processingTime += speedFactor; else this.processingTime += TicksSinceLastCall * speedFactor; } } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } - if ( this.processingTime > this.maxProcessingTime ) + if( this.processingTime > this.maxProcessingTime ) { this.processingTime = this.maxProcessingTime; InscriberRecipe out = this.getTask(); - if ( out != null ) + if( out != null ) { ItemStack is = out.output.copy(); InventoryAdaptor ad = InventoryAdaptor.getAdaptor( new WrapperInventoryRange( this.inv, 3, 1, true ), ForgeDirection.UNKNOWN ); - if ( ad.simulateAdd( is ) == null ) + if( ad.simulateAdd( is ) == null ) { this.smash = true; this.finalStep = 0; @@ -464,10 +464,10 @@ public class TileInscriber extends AENetworkPowerTile implements IGridTickable, @Override public IInventory getInventoryByName( String name ) { - if ( name.equals( "inv" ) ) + if( name.equals( "inv" ) ) return this.inv; - if ( name.equals( "upgrades" ) ) + if( name.equals( "upgrades" ) ) return this.upgrades; return null; diff --git a/src/main/java/appeng/tile/misc/TileInterface.java b/src/main/java/appeng/tile/misc/TileInterface.java index 99d7f40a9..d59c4fc0b 100644 --- a/src/main/java/appeng/tile/misc/TileInterface.java +++ b/src/main/java/appeng/tile/misc/TileInterface.java @@ -18,11 +18,10 @@ package appeng.tile.misc; + import java.util.ArrayList; import java.util.EnumSet; -import com.google.common.collect.ImmutableSet; - import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; @@ -31,6 +30,8 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import com.google.common.collect.ImmutableSet; + import appeng.api.config.Actionable; import appeng.api.config.Upgrades; import appeng.api.implementations.tiles.ITileStorageMonitorable; @@ -62,40 +63,40 @@ import appeng.tile.inventory.InvOperation; import appeng.util.Platform; import appeng.util.inv.IInventoryDestination; -public class TileInterface extends AENetworkInvTile implements IGridTickable, ITileStorageMonitorable, IStorageMonitorable, - IInventoryDestination, IInterfaceHost, IPriorityHost + +public class TileInterface extends AENetworkInvTile implements IGridTickable, ITileStorageMonitorable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, IPriorityHost { - ForgeDirection pointAt = ForgeDirection.UNKNOWN; final DualityInterface duality = new DualityInterface( this.gridProxy, this ); + ForgeDirection pointAt = ForgeDirection.UNKNOWN; @MENetworkEventSubscribe - public void stateChange(MENetworkChannelsChanged c) + public void stateChange( MENetworkChannelsChanged c ) { this.duality.notifyNeighbors(); } @MENetworkEventSubscribe - public void stateChange(MENetworkPowerStatusChange c) + public void stateChange( MENetworkPowerStatusChange c ) { this.duality.notifyNeighbors(); } - public void setSide(ForgeDirection axis) + public void setSide( ForgeDirection axis ) { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; - if ( this.pointAt == axis.getOpposite() ) + if( this.pointAt == axis.getOpposite() ) this.pointAt = axis; - else if ( this.pointAt == axis || this.pointAt == axis.getOpposite() ) + else if( this.pointAt == axis || this.pointAt == axis.getOpposite() ) this.pointAt = ForgeDirection.UNKNOWN; - else if ( this.pointAt == ForgeDirection.UNKNOWN ) + else if( this.pointAt == ForgeDirection.UNKNOWN ) this.pointAt = axis.getOpposite(); else this.pointAt = Platform.rotateAround( this.pointAt, axis ); - if ( ForgeDirection.UNKNOWN == this.pointAt ) + if( ForgeDirection.UNKNOWN == this.pointAt ) this.setOrientation( this.pointAt, this.pointAt ); else this.setOrientation( this.pointAt.offsetY != 0 ? ForgeDirection.SOUTH : ForgeDirection.UP, this.pointAt.getOpposite() ); @@ -106,7 +107,13 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public void getDrops(World w, int x, int y, int z, ArrayList drops) + public void markDirty() + { + this.duality.markDirty(); + } + + @Override + public void getDrops( World w, int x, int y, int z, ArrayList drops ) { this.duality.addDrops( drops ); } @@ -117,26 +124,6 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT this.duality.gridChanged(); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileInterface(NBTTagCompound data) - { - data.setInteger( "pointAt", this.pointAt.ordinal() ); - this.duality.writeToNBT( data ); - } - - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileInterface(NBTTagCompound data) - { - int val = data.getInteger( "pointAt" ); - - if ( val >= 0 && val < ForgeDirection.values().length ) - this.pointAt = ForgeDirection.values()[val]; - else - this.pointAt = ForgeDirection.UNKNOWN; - - this.duality.readFromNBT( data ); - } - @Override public void onReady() { @@ -145,8 +132,28 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT this.duality.initialize(); } + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileInterface( NBTTagCompound data ) + { + data.setInteger( "pointAt", this.pointAt.ordinal() ); + this.duality.writeToNBT( data ); + } + + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileInterface( NBTTagCompound data ) + { + int val = data.getInteger( "pointAt" ); + + if( val >= 0 && val < ForgeDirection.values().length ) + this.pointAt = ForgeDirection.values()[val]; + else + this.pointAt = ForgeDirection.UNKNOWN; + + this.duality.readFromNBT( data ); + } + @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return this.duality.getCableConnectionType( dir ); } @@ -158,13 +165,7 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public TileEntity getTileEntity() - { - return this; - } - - @Override - public boolean canInsert(ItemStack stack) + public boolean canInsert( ItemStack stack ) { return this.duality.canInsert( stack ); } @@ -182,19 +183,19 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public IInventory getInventoryByName(String name) + public IInventory getInventoryByName( String name ) { return this.duality.getInventoryByName( name ); } @Override - public TickingRequest getTickingRequest(IGridNode node) + public TickingRequest getTickingRequest( IGridNode node ) { return this.duality.getTickingRequest( node ); } @Override - public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) + public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) { return this.duality.tickingRequest( node, TicksSinceLastCall ); } @@ -206,19 +207,13 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public void markDirty() - { - this.duality.markDirty(); - } - - @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) { this.duality.onChangeInventory( inv, slot, mc, removed, added ); } @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) + public int[] getAccessibleSlotsBySide( ForgeDirection side ) { return this.duality.getAccessibleSlotsFromSide( side.ordinal() ); } @@ -230,7 +225,21 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src) + public EnumSet getTargets() + { + if( this.pointAt == null || this.pointAt == ForgeDirection.UNKNOWN ) + return EnumSet.complementOf( EnumSet.of( ForgeDirection.UNKNOWN ) ); + return EnumSet.of( this.pointAt ); + } + + @Override + public TileEntity getTileEntity() + { + return this; + } + + @Override + public IStorageMonitorable getMonitorable( ForgeDirection side, BaseActionSource src ) { return this.duality.getMonitorable( side, src, this ); } @@ -242,25 +251,11 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public boolean pushPattern(ICraftingPatternDetails patternDetails, InventoryCrafting table) + public boolean pushPattern( ICraftingPatternDetails patternDetails, InventoryCrafting table ) { return this.duality.pushPattern( patternDetails, table ); } - @Override - public void provideCrafting(ICraftingProviderHelper craftingTracker) - { - this.duality.provideCrafting( craftingTracker ); - } - - @Override - public EnumSet getTargets() - { - if ( this.pointAt == null || this.pointAt == ForgeDirection.UNKNOWN ) - return EnumSet.complementOf( EnumSet.of( ForgeDirection.UNKNOWN ) ); - return EnumSet.of( this.pointAt ); - } - @Override public boolean isBusy() { @@ -268,7 +263,13 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public int getInstalledUpgrades(Upgrades u) + public void provideCrafting( ICraftingProviderHelper craftingTracker ) + { + this.duality.provideCrafting( craftingTracker ); + } + + @Override + public int getInstalledUpgrades( Upgrades u ) { return this.duality.getInstalledUpgrades( u ); } @@ -280,13 +281,13 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public IAEItemStack injectCraftedItems(ICraftingLink link, IAEItemStack items, Actionable mode) + public IAEItemStack injectCraftedItems( ICraftingLink link, IAEItemStack items, Actionable mode ) { return this.duality.injectCraftedItems( link, items, mode ); } @Override - public void jobStateChange(ICraftingLink link) + public void jobStateChange( ICraftingLink link ) { this.duality.jobStateChange( link ); } @@ -298,7 +299,7 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, IT } @Override - public void setPriority(int newValue) + public void setPriority( int newValue ) { this.duality.setPriority( newValue ); } diff --git a/src/main/java/appeng/tile/misc/TileLightDetector.java b/src/main/java/appeng/tile/misc/TileLightDetector.java index c5179c106..3921de190 100644 --- a/src/main/java/appeng/tile/misc/TileLightDetector.java +++ b/src/main/java/appeng/tile/misc/TileLightDetector.java @@ -18,11 +18,13 @@ package appeng.tile.misc; + import appeng.tile.AEBaseTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.util.Platform; + public class TileLightDetector extends AEBaseTile { @@ -34,11 +36,11 @@ public class TileLightDetector extends AEBaseTile return this.lastLight > 0; } - @TileEvent(TileEventType.TICK) + @TileEvent( TileEventType.TICK ) public void Tick_TileLightDetector() { this.lastCheck++; - if ( this.lastCheck > 30 ) + if( this.lastCheck > 30 ) { this.lastCheck = 0; this.updateLight(); @@ -49,7 +51,7 @@ public class TileLightDetector extends AEBaseTile { int val = this.worldObj.getBlockLightValue( this.xCoord, this.yCoord, this.zCoord ); - if ( this.lastLight != val ) + if( this.lastLight != val ) { this.lastLight = val; Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); @@ -61,5 +63,4 @@ public class TileLightDetector extends AEBaseTile { return false; } - } diff --git a/src/main/java/appeng/tile/misc/TilePaint.java b/src/main/java/appeng/tile/misc/TilePaint.java index 5f128e309..5cbab815f 100644 --- a/src/main/java/appeng/tile/misc/TilePaint.java +++ b/src/main/java/appeng/tile/misc/TilePaint.java @@ -18,12 +18,11 @@ package appeng.tile.misc; + import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; -import com.google.common.collect.ImmutableList; - import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -35,6 +34,8 @@ import net.minecraft.util.Vec3; import net.minecraft.world.EnumSkyBlock; import net.minecraftforge.common.util.ForgeDirection; +import com.google.common.collect.ImmutableList; + import appeng.api.util.AEColor; import appeng.helpers.Splotch; import appeng.items.misc.ItemPaintBall; @@ -42,6 +43,7 @@ import appeng.tile.AEBaseTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; + public class TilePaint extends AEBaseTile { @@ -50,9 +52,18 @@ public class TilePaint extends AEBaseTile int isLit = 0; ArrayList dots = null; - void writeBuffer(ByteBuf out) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TilePaint( NBTTagCompound data ) { - if ( this.dots == null ) + ByteBuf myDat = Unpooled.buffer(); + this.writeBuffer( myDat ); + if( myDat.hasArray() ) + data.setByteArray( "dots", myDat.array() ); + } + + void writeBuffer( ByteBuf out ) + { + if( this.dots == null ) { out.writeByte( 0 ); return; @@ -60,15 +71,22 @@ public class TilePaint extends AEBaseTile out.writeByte( this.dots.size() ); - for (Splotch s : this.dots) + for( Splotch s : this.dots ) s.writeToStream( out ); } - void readBuffer(ByteBuf in) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TilePaint( NBTTagCompound data ) + { + if( data.hasKey( "dots" ) ) + this.readBuffer( Unpooled.copiedBuffer( data.getByteArray( "dots" ) ) ); + } + + void readBuffer( ByteBuf in ) { byte howMany = in.readByte(); - if ( howMany == 0 ) + if( howMany == 0 ) { this.isLit = 0; this.dots = null; @@ -76,13 +94,13 @@ public class TilePaint extends AEBaseTile } this.dots = new ArrayList( howMany ); - for (int x = 0; x < howMany; x++) + for( int x = 0; x < howMany; x++ ) this.dots.add( new Splotch( in ) ); this.isLit = 0; - for (Splotch s : this.dots) + for( Splotch s : this.dots ) { - if ( s.lumen ) + if( s.lumen ) { this.isLit += LIGHT_PER_DOT; } @@ -91,30 +109,23 @@ public class TilePaint extends AEBaseTile this.maxLit(); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TilePaint(NBTTagCompound data) + private void maxLit() { - ByteBuf myDat = Unpooled.buffer(); - this.writeBuffer( myDat ); - if ( myDat.hasArray() ) - data.setByteArray( "dots", myDat.array() ); + if( this.isLit > 14 ) + this.isLit = 14; + + if( this.worldObj != null ) + this.worldObj.updateLightByType( EnumSkyBlock.Block, this.xCoord, this.yCoord, this.zCoord ); } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TilePaint(NBTTagCompound data) - { - if ( data.hasKey( "dots" ) ) - this.readBuffer( Unpooled.copiedBuffer( data.getByteArray( "dots" ) ) ); - } - - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TilePaint(ByteBuf data) + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TilePaint( ByteBuf data ) { this.writeBuffer( data ); } - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TilePaint(ByteBuf data) + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TilePaint( ByteBuf data ) { this.readBuffer( data ); return true; @@ -122,61 +133,31 @@ public class TilePaint extends AEBaseTile public void onNeighborBlockChange() { - if ( this.dots == null ) + if( this.dots == null ) return; - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) { - if ( !this.isSideValid( side ) ) + if( !this.isSideValid( side ) ) this.removeSide( side ); } this.updateData(); } - private void updateData() - { - this.isLit = 0; - for (Splotch s : this.dots) - { - if ( s.lumen ) - { - this.isLit += LIGHT_PER_DOT; - } - } - - this.maxLit(); - - if ( this.dots.isEmpty() ) - this.dots = null; - - if ( this.dots == null ) - this.worldObj.setBlock( this.xCoord, this.yCoord, this.zCoord, Blocks.air ); - } - - public void cleanSide(ForgeDirection side) - { - if ( this.dots == null ) - return; - - this.removeSide( side ); - - this.updateData(); - } - - public boolean isSideValid(ForgeDirection side) + public boolean isSideValid( ForgeDirection side ) { Block blk = this.worldObj.getBlock( this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ ); return blk.isSideSolid( this.worldObj, this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ, side.getOpposite() ); } - private void removeSide(ForgeDirection side) + private void removeSide( ForgeDirection side ) { Iterator i = this.dots.iterator(); - while (i.hasNext()) + while( i.hasNext() ) { Splotch s = i.next(); - if ( s.side == side ) + if( s.side == side ) i.remove(); } @@ -184,29 +165,59 @@ public class TilePaint extends AEBaseTile this.markDirty(); } + private void updateData() + { + this.isLit = 0; + for( Splotch s : this.dots ) + { + if( s.lumen ) + { + this.isLit += LIGHT_PER_DOT; + } + } + + this.maxLit(); + + if( this.dots.isEmpty() ) + this.dots = null; + + if( this.dots == null ) + this.worldObj.setBlock( this.xCoord, this.yCoord, this.zCoord, Blocks.air ); + } + + public void cleanSide( ForgeDirection side ) + { + if( this.dots == null ) + return; + + this.removeSide( side ); + + this.updateData(); + } + public int getLightLevel() { return this.isLit; } - public void addBlot(ItemStack type, ForgeDirection side, Vec3 hitVec) + public void addBlot( ItemStack type, ForgeDirection side, Vec3 hitVec ) { Block blk = this.worldObj.getBlock( this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ ); - if ( blk.isSideSolid( this.worldObj, this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ, side.getOpposite() ) ) + if( blk.isSideSolid( this.worldObj, this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ, side.getOpposite() ) ) { ItemPaintBall ipb = (ItemPaintBall) type.getItem(); AEColor col = ipb.getColor( type ); boolean lit = ipb.isLumen( type ); - if ( this.dots == null ) + if( this.dots == null ) this.dots = new ArrayList(); - if ( this.dots.size() > 20 ) + if( this.dots.size() > 20 ) this.dots.remove( 0 ); this.dots.add( new Splotch( col, lit, side, hitVec ) ); - if ( lit ) + if( lit ) this.isLit += LIGHT_PER_DOT; this.maxLit(); @@ -215,18 +226,9 @@ public class TilePaint extends AEBaseTile } } - private void maxLit() - { - if ( this.isLit > 14 ) - this.isLit = 14; - - if ( this.worldObj != null ) - this.worldObj.updateLightByType( EnumSkyBlock.Block, this.xCoord, this.yCoord, this.zCoord ); - } - public Collection getDots() { - if ( this.dots == null ) + if( this.dots == null ) return ImmutableList.of(); return this.dots; diff --git a/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java b/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java index d17327530..94df80909 100644 --- a/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java +++ b/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java @@ -18,6 +18,7 @@ package appeng.tile.misc; + import java.util.EnumSet; import io.netty.buffer.ByteBuf; @@ -35,52 +36,54 @@ import appeng.tile.events.TileEventType; import appeng.tile.grid.AENetworkTile; import appeng.util.Platform; + public class TileQuartzGrowthAccelerator extends AENetworkTile implements IPowerChannelState, ICrystalGrowthAccelerator { public boolean hasPower = false; + public TileQuartzGrowthAccelerator() + { + this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); + this.gridProxy.setFlags(); + this.gridProxy.setIdlePowerUsage( 8 ); + } + @MENetworkEventSubscribe - public void onPower(MENetworkPowerStatusChange ch) + public void onPower( MENetworkPowerStatusChange ch ) { this.markForUpdate(); } @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.COVERED; } - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileQuartzGrowthAccelerator(ByteBuf data) + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileQuartzGrowthAccelerator( ByteBuf data ) { boolean hadPower = this.hasPower; this.hasPower = data.readBoolean(); return this.hasPower != hadPower; } - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileQuartzGrowthAccelerator(ByteBuf data) + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileQuartzGrowthAccelerator( ByteBuf data ) { try { data.writeBoolean( this.gridProxy.getEnergy().isNetworkPowered() ); } - catch (GridAccessException e) + catch( GridAccessException e ) { data.writeBoolean( false ); } } - public TileQuartzGrowthAccelerator() { - this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.gridProxy.setFlags(); - this.gridProxy.setIdlePowerUsage( 8 ); - } - @Override - public void setOrientation(ForgeDirection inForward, ForgeDirection inUp) + public void setOrientation( ForgeDirection inForward, ForgeDirection inUp ) { super.setOrientation( inForward, inUp ); this.gridProxy.setValidSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); @@ -89,13 +92,13 @@ public class TileQuartzGrowthAccelerator extends AENetworkTile implements IPower @Override public boolean isPowered() { - if ( Platform.isServer() ) + if( Platform.isServer() ) { try { return this.gridProxy.getEnergy().isNetworkPowered(); } - catch (GridAccessException e) + catch( GridAccessException e ) { return false; } @@ -109,5 +112,4 @@ public class TileQuartzGrowthAccelerator extends AENetworkTile implements IPower { return this.isPowered(); } - } diff --git a/src/main/java/appeng/tile/misc/TileSecurity.java b/src/main/java/appeng/tile/misc/TileSecurity.java index 2b9988d0e..fc2a6df83 100644 --- a/src/main/java/appeng/tile/misc/TileSecurity.java +++ b/src/main/java/appeng/tile/misc/TileSecurity.java @@ -77,35 +77,47 @@ import appeng.util.IConfigManagerHost; import appeng.util.Platform; import appeng.util.item.AEItemStack; + public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEAppEngInventory, ILocatable, IConfigManagerHost, ISecurityProvider, IColorableTile { private static int difference = 0; + public final AppEngInternalInventory configSlot = new AppEngInternalInventory( this, 1 ); private final IConfigManager cm = new ConfigManager( this ); - private final SecurityInventory inventory = new SecurityInventory( this ); private final MEMonitorHandler securityMonitor = new MEMonitorHandler( this.inventory ); - + public long securityKey; + AEColor paintedColor = AEColor.Transparent; private boolean isActive = false; - AEColor paintedColor = AEColor.Transparent; - public long securityKey; + public TileSecurity() + { + this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); + this.gridProxy.setIdlePowerUsage( 2.0 ); + difference++; - public final AppEngInternalInventory configSlot = new AppEngInternalInventory( this, 1 ); + this.securityKey = System.currentTimeMillis() * 10 + difference; + if( difference > 10 ) + difference = 0; + + this.cm.registerSetting( Settings.SORT_BY, SortOrder.NAME ); + this.cm.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); + this.cm.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); + } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ) { } @Override - public void getDrops(World w, int x, int y, int z, ArrayList drops) + public void getDrops( World w, int x, int y, int z, ArrayList drops ) { - if ( !this.configSlot.isEmpty() ) + if( !this.configSlot.isEmpty() ) drops.add( this.configSlot.getStackInSlot( 0 ) ); - for (IAEItemStack ais : this.inventory.storedItems) + for( IAEItemStack ais : this.inventory.storedItems ) drops.add( ais.getItemStack() ); } @@ -114,35 +126,8 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp return this.inventory; } - @Override - public void onReady() - { - super.onReady(); - if ( Platform.isServer() ) - { - this.isActive = true; - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Register ) ); - } - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - this.isActive = false; - } - - @Override - public void invalidate() - { - super.invalidate(); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - this.isActive = false; - } - - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileSecurity(ByteBuf data) + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileSecurity( ByteBuf data ) { boolean wasActive = this.isActive; this.isActive = data.readBoolean(); @@ -153,15 +138,15 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp return oldPaintedColor != this.paintedColor || wasActive != this.isActive; } - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileSecurity(ByteBuf data) + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileSecurity( ByteBuf data ) { data.writeBoolean( this.gridProxy.isActive() ); data.writeByte( this.paintedColor.ordinal() ); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileSecurity(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileSecurity( NBTTagCompound data ) { this.cm.writeToNBT( data ); data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); @@ -172,7 +157,7 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp NBTTagCompound storedItems = new NBTTagCompound(); int offset = 0; - for (IAEItemStack ais : this.inventory.storedItems) + for( IAEItemStack ais : this.inventory.storedItems ) { NBTTagCompound it = new NBTTagCompound(); ais.getItemStack().writeToNBT( it ); @@ -183,21 +168,21 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp data.setTag( "storedItems", storedItems ); } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileSecurity(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileSecurity( NBTTagCompound data ) { this.cm.readFromNBT( data ); - if ( data.hasKey( "paintedColor" ) ) + if( data.hasKey( "paintedColor" ) ) this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; this.securityKey = data.getLong( "securityKey" ); this.configSlot.readFromNBT( data, "config" ); NBTTagCompound storedItems = data.getCompoundTag( "storedItems" ); - for (Object key : storedItems.func_150296_c()) + for( Object key : storedItems.func_150296_c() ) { NBTBase obj = storedItems.getTag( (String) key ); - if ( obj instanceof NBTTagCompound ) + if( obj instanceof NBTTagCompound ) { this.inventory.storedItems.add( AEItemStack.create( ItemStack.loadItemStackFromNBT( (NBTTagCompound) obj ) ) ); } @@ -211,77 +196,57 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp this.saveChanges(); this.gridProxy.getGrid().postEvent( new MENetworkSecurityChange() ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // :P } } - @Override - public void readPermissions(HashMap> playerPerms) - { - IPlayerRegistry pr = AEApi.instance().registries().players(); - - // read permissions - for (IAEItemStack ais : this.inventory.storedItems) - { - ItemStack is = ais.getItemStack(); - Item i = is.getItem(); - if ( i instanceof IBiometricCard ) - { - IBiometricCard bc = (IBiometricCard) i; - bc.registerPermissions( new PlayerSecurityWrapper( playerPerms ), pr, is ); - } - } - - // make sure thea admin is Boss. - playerPerms.put( this.gridProxy.getNode().getPlayerID(), EnumSet.allOf( SecurityPermissions.class ) ); - } - @MENetworkEventSubscribe - public void bootUpdate(MENetworkChannelsChanged changed) + public void bootUpdate( MENetworkChannelsChanged changed ) { this.markForUpdate(); } @MENetworkEventSubscribe - public void powerUpdate(MENetworkPowerStatusChange changed) + public void powerUpdate( MENetworkPowerStatusChange changed ) { this.markForUpdate(); } @Override - public boolean isSecurityEnabled() - { - return this.isActive && this.gridProxy.isActive(); - } - - public TileSecurity() { - this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); - this.gridProxy.setIdlePowerUsage( 2.0 ); - difference++; - - this.securityKey = System.currentTimeMillis() * 10 + difference; - if ( difference > 10 ) - difference = 0; - - this.cm.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.cm.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.cm.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - } - - @Override - public int getOwner() - { - return this.gridProxy.getNode().getPlayerID(); - } - - @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.SMART; } + @Override + public void onChunkUnload() + { + super.onChunkUnload(); + MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); + this.isActive = false; + } + + @Override + public void onReady() + { + super.onReady(); + if( Platform.isServer() ) + { + this.isActive = true; + MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Register ) ); + } + } + + @Override + public void invalidate() + { + super.invalidate(); + MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); + this.isActive = false; + } + @Override public DimensionalCoord getLocation() { @@ -323,7 +288,7 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp } @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { } @@ -334,6 +299,39 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp return this.securityKey; } + @Override + public void readPermissions( HashMap> playerPerms ) + { + IPlayerRegistry pr = AEApi.instance().registries().players(); + + // read permissions + for( IAEItemStack ais : this.inventory.storedItems ) + { + ItemStack is = ais.getItemStack(); + Item i = is.getItem(); + if( i instanceof IBiometricCard ) + { + IBiometricCard bc = (IBiometricCard) i; + bc.registerPermissions( new PlayerSecurityWrapper( playerPerms ), pr, is ); + } + } + + // make sure thea admin is Boss. + playerPerms.put( this.gridProxy.getNode().getPlayerID(), EnumSet.allOf( SecurityPermissions.class ) ); + } + + @Override + public boolean isSecurityEnabled() + { + return this.isActive && this.gridProxy.isActive(); + } + + @Override + public int getOwner() + { + return this.gridProxy.getNode().getPlayerID(); + } + @Override public AEColor getColor() { @@ -341,9 +339,9 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp } @Override - public boolean recolourBlock(ForgeDirection side, AEColor newPaintedColor, EntityPlayer who) + public boolean recolourBlock( ForgeDirection side, AEColor newPaintedColor, EntityPlayer who ) { - if ( this.paintedColor == newPaintedColor ) + if( this.paintedColor == newPaintedColor ) return false; this.paintedColor = newPaintedColor; @@ -351,5 +349,4 @@ public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEApp this.markForUpdate(); return true; } - } diff --git a/src/main/java/appeng/tile/misc/TileSkyCompass.java b/src/main/java/appeng/tile/misc/TileSkyCompass.java index eb82c7dc7..7937029b1 100644 --- a/src/main/java/appeng/tile/misc/TileSkyCompass.java +++ b/src/main/java/appeng/tile/misc/TileSkyCompass.java @@ -18,8 +18,10 @@ package appeng.tile.misc; + import appeng.tile.AEBaseTile; + public class TileSkyCompass extends AEBaseTile { @@ -28,5 +30,4 @@ public class TileSkyCompass extends AEBaseTile { return true; } - } diff --git a/src/main/java/appeng/tile/misc/TileVibrationChamber.java b/src/main/java/appeng/tile/misc/TileVibrationChamber.java index ef92119f6..a084455c8 100644 --- a/src/main/java/appeng/tile/misc/TileVibrationChamber.java +++ b/src/main/java/appeng/tile/misc/TileVibrationChamber.java @@ -18,6 +18,7 @@ package appeng.tile.misc; + import io.netty.buffer.ByteBuf; import net.minecraft.inventory.IInventory; @@ -42,6 +43,7 @@ import appeng.tile.grid.AENetworkInvTile; import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.InvOperation; + public class TileVibrationChamber extends AENetworkInvTile implements IGridTickable { @@ -57,47 +59,48 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka // client side.. public boolean isOn; + public TileVibrationChamber() + { + this.gridProxy.setIdlePowerUsage( 0 ); + this.gridProxy.setFlags(); + } + @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.COVERED; } - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileVibrationChamber(ByteBuf data) + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileVibrationChamber( ByteBuf data ) { boolean wasOn = this.isOn; this.isOn = data.readBoolean(); return wasOn != this.isOn; // TESR doesn't need updates! } - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileVibrationChamber(ByteBuf data) + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileVibrationChamber( ByteBuf data ) { data.writeBoolean( this.burnTime > 0 ); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileVibrationChamber(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileVibrationChamber( NBTTagCompound data ) { data.setDouble( "burnTime", this.burnTime ); data.setDouble( "maxBurnTime", this.maxBurnTime ); data.setInteger( "burnSpeed", this.burnSpeed ); } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileVibrationChamber(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileVibrationChamber( NBTTagCompound data ) { this.burnTime = data.getDouble( "burnTime" ); this.maxBurnTime = data.getDouble( "maxBurnTime" ); this.burnSpeed = data.getInteger( "burnSpeed" ); } - public TileVibrationChamber() { - this.gridProxy.setIdlePowerUsage( 0 ); - this.gridProxy.setFlags(); - } - @Override public IInventory getInternalInventory() { @@ -105,17 +108,29 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) + public int getInventoryStackLimit() { - if ( this.burnTime <= 0 ) + return 64; + } + + @Override + public boolean isItemValidForSlot( int i, ItemStack itemstack ) + { + return TileEntityFurnace.getItemBurnTime( itemstack ) > 0; + } + + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) + { + if( this.burnTime <= 0 ) { - if ( this.canEatFuel() ) + if( this.canEatFuel() ) { try { this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // wake up! } @@ -124,26 +139,26 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka } @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) + { + return false; + } + + @Override + public int[] getAccessibleSlotsBySide( ForgeDirection side ) { return this.sides; } - @Override - public int getInventoryStackLimit() - { - return 64; - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) - { - return TileEntityFurnace.getItemBurnTime( itemstack ) > 0; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side ) + private boolean canEatFuel() { + ItemStack is = this.getStackInSlot( 0 ); + if( is != null ) + { + int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); + if( newBurnTime > 0 && is.stackSize > 0 ) + return true; + } return false; } @@ -154,22 +169,22 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka } @Override - public TickingRequest getTickingRequest(IGridNode node) + public TickingRequest getTickingRequest( IGridNode node ) { - if ( this.burnTime <= 0 ) + if( this.burnTime <= 0 ) this.eatFuel(); return new TickingRequest( TickRates.VibrationChamber.min, TickRates.VibrationChamber.max, this.burnTime <= 0, false ); } @Override - public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) + public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) { - if ( this.burnTime <= 0 ) + if( this.burnTime <= 0 ) { this.eatFuel(); - if ( this.burnTime > 0 ) + if( this.burnTime > 0 ) return TickRateModulation.URGENT; this.burnSpeed = 100; @@ -181,7 +196,7 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka double timePassed = TicksSinceLastCall * dilation; this.burnTime -= timePassed; - if ( this.burnTime < 0 ) + if( this.burnTime < 0 ) { timePassed += this.burnTime; this.burnTime = 0; @@ -196,7 +211,7 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka // burn the over flow. grid.injectPower( Math.max( 0.0, newPower - overFlow ), Actionable.MODULATE ); - if ( overFlow > 0 ) + if( overFlow > 0 ) this.burnSpeed -= TicksSinceLastCall; else this.burnSpeed += TicksSinceLastCall; @@ -204,7 +219,7 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka this.burnSpeed = Math.max( 20, Math.min( this.burnSpeed, 200 ) ); return overFlow > 0 ? TickRateModulation.SLOWER : TickRateModulation.FASTER; } - catch (GridAccessException e) + catch( GridAccessException e ) { this.burnSpeed -= TicksSinceLastCall; this.burnSpeed = Math.max( 20, Math.min( this.burnSpeed, 200 ) ); @@ -212,34 +227,22 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka } } - private boolean canEatFuel() - { - ItemStack is = this.getStackInSlot( 0 ); - if ( is != null ) - { - int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); - if ( newBurnTime > 0 && is.stackSize > 0 ) - return true; - } - return false; - } - private void eatFuel() { ItemStack is = this.getStackInSlot( 0 ); - if ( is != null ) + if( is != null ) { int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); - if ( newBurnTime > 0 && is.stackSize > 0 ) + if( newBurnTime > 0 && is.stackSize > 0 ) { this.burnTime += newBurnTime; this.maxBurnTime = this.burnTime; is.stackSize--; - if ( is.stackSize <= 0 ) + if( is.stackSize <= 0 ) { ItemStack container = null; - if ( is.getItem().hasContainerItem( is ) ) + if( is.getItem().hasContainerItem( is ) ) container = is.getItem().getContainerItem( is ); this.setInventorySlotContents( 0, container ); @@ -249,19 +252,19 @@ public class TileVibrationChamber extends AENetworkInvTile implements IGridTicka } } - if ( this.burnTime > 0 ) + if( this.burnTime > 0 ) { try { this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // gah! } } - if ( (!this.isOn && this.burnTime > 0) || (this.isOn && this.burnTime <= 0) ) + if( ( !this.isOn && this.burnTime > 0 ) || ( this.isOn && this.burnTime <= 0 ) ) { this.isOn = this.burnTime > 0; this.markForUpdate(); diff --git a/src/main/java/appeng/tile/networking/TileCableBus.java b/src/main/java/appeng/tile/networking/TileCableBus.java index 29319c109..f94e1c848 100644 --- a/src/main/java/appeng/tile/networking/TileCableBus.java +++ b/src/main/java/appeng/tile/networking/TileCableBus.java @@ -18,6 +18,7 @@ package appeng.tile.networking; + import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -56,31 +57,37 @@ import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.util.Platform; + public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomCollision { public CableBusContainer cb = new CableBusContainer( this ); + /** + * Immibis MB Support + */ + + boolean ImmibisMicroblocks_TransformableTileEntityMarker = true; private int oldLV = -1; // on re-calculate light when it changes - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileCableBus(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileCableBus( NBTTagCompound data ) { this.cb.readFromNBT( data ); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileCableBus(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileCableBus( NBTTagCompound data ) { this.cb.writeToNBT( data ); } - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileCableBus(ByteBuf data) throws IOException + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileCableBus( ByteBuf data ) throws IOException { boolean ret = this.cb.readFromStream( data ); int newLV = this.cb.getLightValue(); - if ( newLV != this.oldLV ) + if( newLV != this.oldLV ) { this.oldLV = newLV; this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); @@ -91,21 +98,9 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl return ret; } - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileCableBus(ByteBuf data) throws IOException - { - this.cb.writeToStream( data ); - } - - @Override - public boolean isInWorld() - { - return this.cb.isInWorld(); - } - protected void updateTileSetting() { - if ( this.cb.requiresDynamicRender ) + if( this.cb.requiresDynamicRender ) { TileCableBus tcb; try @@ -114,14 +109,14 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl tcb.copyFrom( this ); this.getWorldObj().setTileEntity( this.xCoord, this.yCoord, this.zCoord, tcb ); } - catch (Throwable ignored) + catch( Throwable ignored ) { } } } - protected void copyFrom(TileCableBus oldTile) + protected void copyFrom( TileCableBus oldTile ) { CableBusContainer tmpCB = this.cb; this.cb = oldTile.cb; @@ -129,23 +124,22 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl oldTile.cb = tmpCB; } - @Override - public void onReady() + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileCableBus( ByteBuf data ) throws IOException { - super.onReady(); - if ( this.cb.isEmpty() ) - { - if ( this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord ) == this ) - this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, true ); - } - else - this.cb.addToWorld(); + this.cb.writeToStream( data ); } @Override - public void onChunkUnload() + public double getMaxRenderDistanceSquared() { - super.onChunkUnload(); + return 900.0; + } + + @Override + public void invalidate() + { + super.invalidate(); this.cb.removeFromWorld(); } @@ -157,70 +151,15 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl } @Override - public void invalidate() - { - super.invalidate(); - this.cb.removeFromWorld(); - } - - @Override - public boolean canBeRotated() - { - return false; - } - - @Override - public double getMaxRenderDistanceSquared() - { - return 900.0; - } - - @Override - public void getDrops(World w, int x, int y, int z, ArrayList drops) - { - this.cb.getDrops( drops ); - } - - @Override - public void getNoDrops(World w, int x, int y, int z, ArrayList drops) - { - this.cb.getNoDrops( drops ); - } - - @Override - public IGridNode getGridNode(ForgeDirection dir) + public IGridNode getGridNode( ForgeDirection dir ) { return this.cb.getGridNode( dir ); } @Override - public boolean canAddPart(ItemStack is, ForgeDirection side) + public AECableType getCableConnectionType( ForgeDirection side ) { - return this.cb.canAddPart( is, side ); - } - - @Override - public ForgeDirection addPart(ItemStack is, ForgeDirection side, EntityPlayer player) - { - return this.cb.addPart( is, side, player ); - } - - @Override - public void removePart(ForgeDirection side, boolean suppressUpdate) - { - this.cb.removePart( side, suppressUpdate ); - } - - @Override - public IPart getPart(ForgeDirection side) - { - return this.cb.getPart( side ); - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); + return this.cb.getCableConnectionType( side ); } @Override @@ -230,56 +169,20 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl } @Override - public Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity e, boolean visual) + public void onChunkUnload() { - return this.cb.getSelectedBoundingBoxesFromPool( false, true, e, visual ); - } - - @Override - public void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e) - { - for (AxisAlignedBB bx : this.getSelectedBoundingBoxesFromPool( w, x, y, z, e, false )) - out.add( AxisAlignedBB.getBoundingBox( bx.minX, bx.minY, bx.minZ, bx.maxX, bx.maxY, bx.maxZ ) ); - } - - @Override - public AECableType getCableConnectionType(ForgeDirection side) - { - return this.cb.getCableConnectionType( side ); - } - - @Override - public AEColor getColor() - { - return this.cb.getColor(); - } - - @Override - public IFacadeContainer getFacadeContainer() - { - return this.cb.getFacadeContainer(); - } - - @Override - public void clearContainer() - { - this.cb = new CableBusContainer( this ); - } - - @Override - public boolean isBlocked(ForgeDirection side) - { - return !this.ImmibisMicroblocks_isSideOpen( side.ordinal() ); + super.onChunkUnload(); + this.cb.removeFromWorld(); } @Override public void markForUpdate() { - if ( this.worldObj == null ) + if( this.worldObj == null ) return; int newLV = this.cb.getLightValue(); - if ( newLV != this.oldLV ) + if( newLV != this.oldLV ) { this.oldLV = newLV; this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); @@ -290,24 +193,106 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl } @Override - public SelectedPart selectPart(Vec3 pos) + public boolean canBeRotated() + { + return false; + } + + @Override + public void getDrops( World w, int x, int y, int z, ArrayList drops ) + { + this.cb.getDrops( drops ); + } + + @Override + public void getNoDrops( World w, int x, int y, int z, ArrayList drops ) + { + this.cb.getNoDrops( drops ); + } + + @Override + public void onReady() + { + super.onReady(); + if( this.cb.isEmpty() ) + { + if( this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord ) == this ) + this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, true ); + } + else + this.cb.addToWorld(); + } + + @Override + public boolean requiresTESR() + { + return this.cb.requiresDynamicRender; + } + + @Override + public IFacadeContainer getFacadeContainer() + { + return this.cb.getFacadeContainer(); + } + + @Override + public boolean canAddPart( ItemStack is, ForgeDirection side ) + { + return this.cb.canAddPart( is, side ); + } + + @Override + public ForgeDirection addPart( ItemStack is, ForgeDirection side, EntityPlayer player ) + { + return this.cb.addPart( is, side, player ); + } + + @Override + public IPart getPart( ForgeDirection side ) + { + return this.cb.getPart( side ); + } + + @Override + public void removePart( ForgeDirection side, boolean suppressUpdate ) + { + this.cb.removePart( side, suppressUpdate ); + } + + @Override + public DimensionalCoord getLocation() + { + return new DimensionalCoord( this ); + } + + @Override + public AEColor getColor() + { + return this.cb.getColor(); + } + + @Override + public void clearContainer() + { + this.cb = new CableBusContainer( this ); + } + + @Override + public boolean isBlocked( ForgeDirection side ) + { + return !this.ImmibisMicroblocks_isSideOpen( side.ordinal() ); + } @Override + public Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity e, boolean visual ) + { + return this.cb.getSelectedBoundingBoxesFromPool( false, true, e, visual ); + } + + @Override + public SelectedPart selectPart( Vec3 pos ) { return this.cb.selectPart( pos ); } - @Override - public void partChanged() - { - this.notifyNeighbors(); - } - - @Override - public void notifyNeighbors() - { - if ( this.worldObj != null && this.worldObj.blockExists( this.xCoord, this.yCoord, this.zCoord ) && !CableBusContainer.isLoading() ) - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - @Override public void markForSave() { @@ -315,7 +300,13 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl } @Override - public boolean hasRedstone(ForgeDirection side) + public void partChanged() + { + this.notifyNeighbors(); + } + + @Override + public boolean hasRedstone( ForgeDirection side ) { return this.cb.hasRedstone( side ); } @@ -326,12 +317,6 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl return this.cb.isEmpty(); } - @Override - public boolean requiresTESR() - { - return this.cb.requiresDynamicRender; - } - @Override public Set getLayerFlags() { @@ -341,23 +326,35 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl @Override public void cleanup() { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.ImmibisMicroblocks ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.ImmibisMicroblocks ) ) { IImmibisMicroblocks imb = (IImmibisMicroblocks) AppEng.instance.getIntegration( IntegrationType.ImmibisMicroblocks ); - if ( imb != null && imb.leaveParts( this ) ) + if( imb != null && imb.leaveParts( this ) ) return; } this.getWorldObj().setBlock( this.xCoord, this.yCoord, this.zCoord, Platform.AIR ); + } @Override + public void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ) + { + for( AxisAlignedBB bx : this.getSelectedBoundingBoxesFromPool( w, x, y, z, e, false ) ) + out.add( AxisAlignedBB.getBoundingBox( bx.minX, bx.minY, bx.minZ, bx.maxX, bx.maxY, bx.maxZ ) ); } - /** - * Immibis MB Support - */ + @Override + public void notifyNeighbors() + { + if( this.worldObj != null && this.worldObj.blockExists( this.xCoord, this.yCoord, this.zCoord ) && !CableBusContainer.isLoading() ) + Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); + } - boolean ImmibisMicroblocks_TransformableTileEntityMarker = true; + @Override + public boolean isInWorld() + { + return this.cb.isInWorld(); + } - public boolean ImmibisMicroblocks_isSideOpen(int side) + public boolean ImmibisMicroblocks_isSideOpen( int side ) { return true; } @@ -368,9 +365,12 @@ public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomColl } @Override - public boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who) + public boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ) { return this.cb.recolourBlock( side, colour, who ); } + + + } diff --git a/src/main/java/appeng/tile/networking/TileCableBusTESR.java b/src/main/java/appeng/tile/networking/TileCableBusTESR.java index 959f7eb0b..e0bb7368c 100644 --- a/src/main/java/appeng/tile/networking/TileCableBusTESR.java +++ b/src/main/java/appeng/tile/networking/TileCableBusTESR.java @@ -18,15 +18,17 @@ package appeng.tile.networking; + import appeng.block.networking.BlockCableBus; + public class TileCableBusTESR extends TileCableBus { @Override protected void updateTileSetting() { - if ( !this.cb.requiresDynamicRender ) + if( !this.cb.requiresDynamicRender ) { TileCableBus tcb; try @@ -35,11 +37,10 @@ public class TileCableBusTESR extends TileCableBus tcb.copyFrom( this ); this.getWorldObj().setTileEntity( this.xCoord, this.yCoord, this.zCoord, tcb ); } - catch (Throwable ignored) + catch( Throwable ignored ) { } } } - } diff --git a/src/main/java/appeng/tile/networking/TileController.java b/src/main/java/appeng/tile/networking/TileController.java index 2e2536975..74374da0c 100644 --- a/src/main/java/appeng/tile/networking/TileController.java +++ b/src/main/java/appeng/tile/networking/TileController.java @@ -18,6 +18,7 @@ package appeng.tile.networking; + import java.util.EnumSet; import net.minecraft.inventory.IInventory; @@ -38,12 +39,16 @@ import appeng.tile.grid.AENetworkPowerTile; import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.InvOperation; + public class TileController extends AENetworkPowerTile { + static final AppEngInternalInventory inv = new AppEngInternalInventory( null, 0 ); + final int[] sides = new int[] {}; boolean isValid = false; - public TileController() { + public TileController() + { this.internalMaxPower = 8000; this.internalPublicPowerStorage = true; this.gridProxy.setIdlePowerUsage( 3 ); @@ -51,67 +56,11 @@ public class TileController extends AENetworkPowerTile } @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.DENSE; } - @Override - protected double getFunnelPowerDemand(double maxReceived) - { - try - { - return this.gridProxy.getEnergy().getEnergyDemand( 8000 ); - } - catch (GridAccessException e) - { - // no grid? use local... - return super.getFunnelPowerDemand( maxReceived ); - } - } - - @Override - protected double funnelPowerIntoStorage(double AEUnits, Actionable mode) - { - try - { - double ret = this.gridProxy.getEnergy().injectPower( AEUnits, mode ); - if ( mode == Actionable.SIMULATE ) - return ret; - return 0; - } - catch (GridAccessException e) - { - // no grid? use local... - return super.funnelPowerIntoStorage( AEUnits, mode ); - } - } - - @Override - protected void PowerEvent(PowerEventType x) - { - try - { - this.gridProxy.getGrid().postEvent( new MENetworkPowerStorage( this, x ) ); - } - catch (GridAccessException e) - { - // not ready! - } - } - - @MENetworkEventSubscribe - public void onControllerChange(MENetworkControllerChange status) - { - this.updateMeta(); - } - - @MENetworkEventSubscribe - public void onPowerChange(MENetworkPowerStatusChange status) - { - this.updateMeta(); - } - @Override public void onReady() { @@ -119,14 +68,11 @@ public class TileController extends AENetworkPowerTile super.onReady(); } - public void onNeighborChange(boolean force) + public void onNeighborChange( boolean force ) { - boolean xx = this.worldObj.getTileEntity( this.xCoord - 1, this.yCoord, this.zCoord ) instanceof TileController - && this.worldObj.getTileEntity( this.xCoord + 1, this.yCoord, this.zCoord ) instanceof TileController; - boolean yy = this.worldObj.getTileEntity( this.xCoord, this.yCoord - 1, this.zCoord ) instanceof TileController - && this.worldObj.getTileEntity( this.xCoord, this.yCoord + 1, this.zCoord ) instanceof TileController; - boolean zz = this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord - 1 ) instanceof TileController - && this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord + 1 ) instanceof TileController; + boolean xx = this.worldObj.getTileEntity( this.xCoord - 1, this.yCoord, this.zCoord ) instanceof TileController && this.worldObj.getTileEntity( this.xCoord + 1, this.yCoord, this.zCoord ) instanceof TileController; + boolean yy = this.worldObj.getTileEntity( this.xCoord, this.yCoord - 1, this.zCoord ) instanceof TileController && this.worldObj.getTileEntity( this.xCoord, this.yCoord + 1, this.zCoord ) instanceof TileController; + boolean zz = this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord - 1 ) instanceof TileController && this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord + 1 ) instanceof TileController; // int meta = world.getBlockMetadata( xCoord, yCoord, zCoord ); // boolean hasPower = meta > 0; @@ -134,11 +80,11 @@ public class TileController extends AENetworkPowerTile boolean oldValid = this.isValid; - this.isValid = (xx && !yy && !zz) || (!xx && yy && !zz) || (!xx && !yy && zz) || ((xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) <= 1); + this.isValid = ( xx && !yy && !zz ) || ( !xx && yy && !zz ) || ( !xx && !yy && zz ) || ( ( xx ? 1 : 0 ) + ( yy ? 1 : 0 ) + ( zz ? 1 : 0 ) <= 1 ); - if ( oldValid != this.isValid || force ) + if( oldValid != this.isValid || force ) { - if ( this.isValid ) + if( this.isValid ) this.gridProxy.setValidSides( EnumSet.allOf( ForgeDirection.class ) ); else this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); @@ -149,22 +95,22 @@ public class TileController extends AENetworkPowerTile private void updateMeta() { - if ( !this.gridProxy.isReady() ) + if( !this.gridProxy.isReady() ) return; int meta = 0; try { - if ( this.gridProxy.getEnergy().isNetworkPowered() ) + if( this.gridProxy.getEnergy().isNetworkPowered() ) { meta = 1; - if ( this.gridProxy.getPath().getControllerState() == ControllerState.CONTROLLER_CONFLICT ) + if( this.gridProxy.getPath().getControllerState() == ControllerState.CONTROLLER_CONFLICT ) meta = 2; } } - catch (GridAccessException e) + catch( GridAccessException e ) { meta = 0; } @@ -172,8 +118,61 @@ public class TileController extends AENetworkPowerTile this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, meta, 2 ); } - final int[] sides = new int[] { }; - static final AppEngInternalInventory inv = new AppEngInternalInventory( null, 0 ); + @Override + protected double getFunnelPowerDemand( double maxReceived ) + { + try + { + return this.gridProxy.getEnergy().getEnergyDemand( 8000 ); + } + catch( GridAccessException e ) + { + // no grid? use local... + return super.getFunnelPowerDemand( maxReceived ); + } + } + + @Override + protected double funnelPowerIntoStorage( double AEUnits, Actionable mode ) + { + try + { + double ret = this.gridProxy.getEnergy().injectPower( AEUnits, mode ); + if( mode == Actionable.SIMULATE ) + return ret; + return 0; + } + catch( GridAccessException e ) + { + // no grid? use local... + return super.funnelPowerIntoStorage( AEUnits, mode ); + } + } + + @Override + protected void PowerEvent( PowerEventType x ) + { + try + { + this.gridProxy.getGrid().postEvent( new MENetworkPowerStorage( this, x ) ); + } + catch( GridAccessException e ) + { + // not ready! + } + } + + @MENetworkEventSubscribe + public void onControllerChange( MENetworkControllerChange status ) + { + this.updateMeta(); + } + + @MENetworkEventSubscribe + public void onPowerChange( MENetworkPowerStatusChange status ) + { + this.updateMeta(); + } @Override public IInventory getInternalInventory() @@ -182,15 +181,14 @@ public class TileController extends AENetworkPowerTile } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) { } @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) + public int[] getAccessibleSlotsBySide( ForgeDirection side ) { return this.sides; } - } diff --git a/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java b/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java index 4bd52549a..247be2ebf 100644 --- a/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java @@ -18,6 +18,7 @@ package appeng.tile.networking; + import net.minecraftforge.common.util.ForgeDirection; import appeng.api.config.AccessRestriction; @@ -27,31 +28,27 @@ import appeng.api.networking.energy.IAEPowerStorage; import appeng.api.util.AECableType; import appeng.tile.grid.AENetworkTile; + public class TileCreativeEnergyCell extends AENetworkTile implements IAEPowerStorage { - public TileCreativeEnergyCell() { + public TileCreativeEnergyCell() + { this.gridProxy.setIdlePowerUsage( 0 ); } @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.COVERED; } @Override - public double injectAEPower(double amt, Actionable mode) + public double injectAEPower( double amt, Actionable mode ) { return 0; } - @Override - public double extractAEPower(double amt, Actionable mode, PowerMultiplier pm) - { - return amt; - } - @Override public double getAEMaxPower() { @@ -76,4 +73,9 @@ public class TileCreativeEnergyCell extends AENetworkTile implements IAEPowerSto return AccessRestriction.READ_WRITE; } + @Override + public double extractAEPower( double amt, Actionable mode, PowerMultiplier pm ) + { + return amt; + } } diff --git a/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java b/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java index 8e4e842e2..32eb4ee71 100644 --- a/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java @@ -18,11 +18,12 @@ package appeng.tile.networking; + public class TileDenseEnergyCell extends TileEnergyCell { - public TileDenseEnergyCell() { + public TileDenseEnergyCell() + { this.internalMaxPower = 200000 * 8; } - } diff --git a/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java b/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java index 765acf843..07a468ccf 100644 --- a/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java +++ b/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java @@ -37,7 +37,7 @@ public class TileEnergyAcceptor extends AENetworkPowerTile { final static AppEngInternalInventory INTERNAL_INVENTORY = new AppEngInternalInventory( null, 0 ); - final int[] sides = new int[] { }; + final int[] sides = new int[] {}; public TileEnergyAcceptor() { @@ -45,12 +45,6 @@ public class TileEnergyAcceptor extends AENetworkPowerTile this.internalMaxPower = 0; } - @Override - public AECableType getCableConnectionType( ForgeDirection dir ) - { - return AECableType.COVERED; - } - @Override public void readFromNBT_AENetwork( NBTTagCompound data ) { @@ -67,6 +61,12 @@ public class TileEnergyAcceptor extends AENetworkPowerTile */ } + @Override + public AECableType getCableConnectionType( ForgeDirection dir ) + { + return AECableType.COVERED; + } + @Override protected double getFunnelPowerDemand( double maxRequired ) { @@ -75,7 +75,7 @@ public class TileEnergyAcceptor extends AENetworkPowerTile IEnergyGrid grid = this.gridProxy.getEnergy(); return grid.getEnergyDemand( maxRequired ); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { return this.internalMaxPower; } @@ -88,11 +88,11 @@ public class TileEnergyAcceptor extends AENetworkPowerTile { IEnergyGrid grid = this.gridProxy.getEnergy(); double leftOver = grid.injectPower( newPower, mode ); - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) return leftOver; return 0.0; } - catch ( GridAccessException e ) + catch( GridAccessException e ) { return super.funnelPowerIntoStorage( newPower, mode ); } diff --git a/src/main/java/appeng/tile/networking/TileEnergyCell.java b/src/main/java/appeng/tile/networking/TileEnergyCell.java index d96fafa3e..f3ac558ab 100644 --- a/src/main/java/appeng/tile/networking/TileEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileEnergyCell.java @@ -18,6 +18,7 @@ package appeng.tile.networking; + import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; @@ -34,6 +35,7 @@ import appeng.tile.events.TileEventType; import appeng.tile.grid.AENetworkTile; import appeng.util.SettingsFrom; + public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage { @@ -42,48 +44,57 @@ public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage private byte currentMeta = -1; + public TileEnergyCell() + { + this.gridProxy.setIdlePowerUsage( 0 ); + } + @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.COVERED; } + @Override + public void onReady() + { + super.onReady(); + this.currentMeta = (byte) this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ); + this.changePowerLevel(); + } + private void changePowerLevel() { - if ( this.notLoaded() ) + if( this.notLoaded() ) return; - byte boundMetadata = (byte) (8.0 * (this.internalCurrentPower / this.internalMaxPower)); + byte boundMetadata = (byte) ( 8.0 * ( this.internalCurrentPower / this.internalMaxPower ) ); - if ( boundMetadata > 7 ) + if( boundMetadata > 7 ) boundMetadata = 7; - if ( boundMetadata < 0 ) + if( boundMetadata < 0 ) boundMetadata = 0; - if ( this.currentMeta != boundMetadata ) + if( this.currentMeta != boundMetadata ) { this.currentMeta = boundMetadata; this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, this.currentMeta, 2 ); } } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileEnergyCell(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileEnergyCell( NBTTagCompound data ) { - if ( !this.worldObj.isRemote ) + if( !this.worldObj.isRemote ) data.setDouble( "internalCurrentPower", this.internalCurrentPower ); } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileEnergyCell(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileEnergyCell( NBTTagCompound data ) { this.internalCurrentPower = data.getDouble( "internalCurrentPower" ); } - public TileEnergyCell() { - this.gridProxy.setIdlePowerUsage( 0 ); - } - @Override public boolean canBeRotated() { @@ -91,12 +102,34 @@ public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage } @Override - final public double injectAEPower(double amt, Actionable mode) + public void uploadSettings( SettingsFrom from, NBTTagCompound compound ) { - if ( mode == Actionable.SIMULATE ) + if( from == SettingsFrom.DISMANTLE_ITEM ) + { + this.internalCurrentPower = compound.getDouble( "internalCurrentPower" ); + } + } + + @Override + public NBTTagCompound downloadSettings( SettingsFrom from ) + { + if( from == SettingsFrom.DISMANTLE_ITEM ) + { + NBTTagCompound tag = new NBTTagCompound(); + tag.setDouble( "internalCurrentPower", this.internalCurrentPower ); + tag.setDouble( "internalMaxPower", this.internalMaxPower ); // used for tool tip. + return tag; + } + return null; + } + + @Override + final public double injectAEPower( double amt, Actionable mode ) + { + if( mode == Actionable.SIMULATE ) { double fakeBattery = this.internalCurrentPower + amt; - if ( fakeBattery > this.internalMaxPower ) + if( fakeBattery > this.internalMaxPower ) { return fakeBattery - this.internalMaxPower; } @@ -104,11 +137,11 @@ public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage return 0; } - if ( this.internalCurrentPower < 0.01 && amt > 0.01 ) + if( this.internalCurrentPower < 0.01 && amt > 0.01 ) this.gridProxy.getNode().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.PROVIDE_POWER ) ); this.internalCurrentPower += amt; - if ( this.internalCurrentPower > this.internalMaxPower ) + if( this.internalCurrentPower > this.internalMaxPower ) { amt = this.internalCurrentPower - this.internalMaxPower; this.internalCurrentPower = this.internalMaxPower; @@ -121,50 +154,6 @@ public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage return 0; } - private double extractAEPower(double amt, Actionable mode) - { - if ( mode == Actionable.SIMULATE ) - { - if ( this.internalCurrentPower > amt ) - return amt; - return this.internalCurrentPower; - } - - boolean wasFull = this.internalCurrentPower >= this.internalMaxPower - 0.001; - - if ( wasFull && amt > 0.001 ) - { - try - { - this.gridProxy.getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - catch (GridAccessException ignored) - { - - } - } - - if ( this.internalCurrentPower > amt ) - { - this.internalCurrentPower -= amt; - - this.changePowerLevel(); - return amt; - } - - amt = this.internalCurrentPower; - this.internalCurrentPower = 0; - - this.changePowerLevel(); - return amt; - } - - @Override - final public double extractAEPower(double amt, Actionable mode, PowerMultiplier pm) - { - return pm.divide( this.extractAEPower( pm.multiply( amt ), mode ) ); - } - @Override public double getAEMaxPower() { @@ -190,32 +179,46 @@ public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage } @Override - public void onReady() + final public double extractAEPower( double amt, Actionable mode, PowerMultiplier pm ) { - super.onReady(); - this.currentMeta = (byte) this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ); + return pm.divide( this.extractAEPower( pm.multiply( amt ), mode ) ); + } + + private double extractAEPower( double amt, Actionable mode ) + { + if( mode == Actionable.SIMULATE ) + { + if( this.internalCurrentPower > amt ) + return amt; + return this.internalCurrentPower; + } + + boolean wasFull = this.internalCurrentPower >= this.internalMaxPower - 0.001; + + if( wasFull && amt > 0.001 ) + { + try + { + this.gridProxy.getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); + } + catch( GridAccessException ignored ) + { + + } + } + + if( this.internalCurrentPower > amt ) + { + this.internalCurrentPower -= amt; + + this.changePowerLevel(); + return amt; + } + + amt = this.internalCurrentPower; + this.internalCurrentPower = 0; + this.changePowerLevel(); - } - - @Override - public NBTTagCompound downloadSettings(SettingsFrom from) - { - if ( from == SettingsFrom.DISMANTLE_ITEM ) - { - NBTTagCompound tag = new NBTTagCompound(); - tag.setDouble( "internalCurrentPower", this.internalCurrentPower ); - tag.setDouble( "internalMaxPower", this.internalMaxPower ); // used for tool tip. - return tag; - } - return null; - } - - @Override - public void uploadSettings(SettingsFrom from, NBTTagCompound compound) - { - if ( from == SettingsFrom.DISMANTLE_ITEM ) - { - this.internalCurrentPower = compound.getDouble( "internalCurrentPower" ); - } + return amt; } } diff --git a/src/main/java/appeng/tile/networking/TileWireless.java b/src/main/java/appeng/tile/networking/TileWireless.java index d6d5f7b70..7b5a5c8c6 100644 --- a/src/main/java/appeng/tile/networking/TileWireless.java +++ b/src/main/java/appeng/tile/networking/TileWireless.java @@ -1,4 +1,3 @@ - /* * This file is part of Applied Energistics 2. * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. @@ -100,18 +99,18 @@ public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoi try { - if ( this.gridProxy.getEnergy().isNetworkPowered() ) + if( this.gridProxy.getEnergy().isNetworkPowered() ) this.clientFlags |= POWERED_FLAG; - if ( this.gridProxy.getNode().meetsChannelRequirements() ) + if( this.gridProxy.getNode().meetsChannelRequirements() ) this.clientFlags |= CHANNEL_FLAG; } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // meh } - data.writeByte( ( byte ) this.clientFlags ); + data.writeByte( (byte) this.clientFlags ); } @Override @@ -132,64 +131,6 @@ public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoi return this.inv; } - @Override - public void onReady() - { - this.updatePower(); - super.onReady(); - } - - @Override - public void markDirty() - { - this.updatePower(); - } - - private void updatePower() - { - this.gridProxy.setIdlePowerUsage( AEConfig.instance.wireless_getPowerDrain( this.getBoosters() ) ); - } - - @Override - public int[] getAccessibleSlotsBySide( ForgeDirection side ) - { - return this.sides; - } - - @Override - public double getRange() - { - return AEConfig.instance.wireless_getMaxRange( this.getBoosters() ); - } - - @Override - public boolean isActive() - { - if ( Platform.isClient() ) - return this.isPowered() && ( CHANNEL_FLAG == ( this.clientFlags & CHANNEL_FLAG ) ); - - return this.gridProxy.isActive(); - } - - @Override - public IGrid getGrid() - { - try - { - return this.gridProxy.getGrid(); - } - catch ( GridAccessException e ) - { - return null; - } - } - - private int getBoosters() - { - ItemStack boosters = this.inv.getStackInSlot( 0 ); - return boosters == null ? 0 : boosters.stackSize; - } - @Override public boolean isItemValidForSlot( int i, ItemStack itemstack ) { @@ -202,10 +143,67 @@ public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoi // :P } + @Override + public int[] getAccessibleSlotsBySide( ForgeDirection side ) + { + return this.sides; + } + + @Override + public void onReady() + { + this.updatePower(); + super.onReady(); + } + + private void updatePower() + { + this.gridProxy.setIdlePowerUsage( AEConfig.instance.wireless_getPowerDrain( this.getBoosters() ) ); + } + + private int getBoosters() + { + ItemStack boosters = this.inv.getStackInSlot( 0 ); + return boosters == null ? 0 : boosters.stackSize; + } + + @Override + public void markDirty() + { + this.updatePower(); + } + + @Override + public double getRange() + { + return AEConfig.instance.wireless_getMaxRange( this.getBoosters() ); + } + + @Override + public boolean isActive() + { + if( Platform.isClient() ) + return this.isPowered() && ( CHANNEL_FLAG == ( this.clientFlags & CHANNEL_FLAG ) ); + + return this.gridProxy.isActive(); + } + + @Override + public IGrid getGrid() + { + try + { + return this.gridProxy.getGrid(); + } + catch( GridAccessException e ) + { + return null; + } + } + @Override public boolean isPowered() { return POWERED_FLAG == ( this.clientFlags & POWERED_FLAG ); } - } diff --git a/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java b/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java index fee7b8fc9..592a72411 100644 --- a/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java +++ b/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java @@ -18,6 +18,7 @@ package appeng.tile.powersink; + public abstract class AEBasePoweredTile extends MekJoules { diff --git a/src/main/java/appeng/tile/powersink/AERootPoweredTile.java b/src/main/java/appeng/tile/powersink/AERootPoweredTile.java index 35678f6ca..752cee37d 100644 --- a/src/main/java/appeng/tile/powersink/AERootPoweredTile.java +++ b/src/main/java/appeng/tile/powersink/AERootPoweredTile.java @@ -18,6 +18,7 @@ package appeng.tile.powersink; + import java.util.EnumSet; import net.minecraft.nbt.NBTTagCompound; @@ -33,86 +34,85 @@ import appeng.tile.AEBaseInvTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; + public abstract class AERootPoweredTile extends AEBaseInvTile implements IAEPowerStorage { + protected final boolean internalCanAcceptPower = true; // values that determine general function, are set by inheriting classes if // needed. These should generally remain static. protected double internalMaxPower = 10000; - protected final boolean internalCanAcceptPower = true; protected boolean internalPublicPowerStorage = false; - private EnumSet internalPowerSides = EnumSet.allOf( ForgeDirection.class ); - protected AccessRestriction internalPowerFlow = AccessRestriction.READ_WRITE; - // the current power buffer. protected double internalCurrentPower = 0; - - protected void setPowerSides(EnumSet sides) - { - this.internalPowerSides = sides; - // trigger re-calc! - } + private EnumSet internalPowerSides = EnumSet.allOf( ForgeDirection.class ); protected EnumSet getPowerSides() { return this.internalPowerSides.clone(); } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_AERootPoweredTile(NBTTagCompound data) + protected void setPowerSides( EnumSet sides ) + { + this.internalPowerSides = sides; + // trigger re-calc! + } + + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_AERootPoweredTile( NBTTagCompound data ) { data.setDouble( "internalCurrentPower", this.internalCurrentPower ); } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_AERootPoweredTile(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_AERootPoweredTile( NBTTagCompound data ) { this.internalCurrentPower = data.getDouble( "internalCurrentPower" ); } - final protected double getExternalPowerDemand(PowerUnits externalUnit, double maxPowerRequired) + final protected double getExternalPowerDemand( PowerUnits externalUnit, double maxPowerRequired ) { return PowerUnits.AE.convertTo( externalUnit, Math.max( 0.0, this.getFunnelPowerDemand( externalUnit.convertTo( PowerUnits.AE, maxPowerRequired ) ) ) ); } - protected double getFunnelPowerDemand(double maxRequired) + protected double getFunnelPowerDemand( double maxRequired ) { return this.internalMaxPower - this.internalCurrentPower; } - final public double injectExternalPower(PowerUnits input, double amt) + final public double injectExternalPower( PowerUnits input, double amt ) { return PowerUnits.AE.convertTo( input, this.funnelPowerIntoStorage( input.convertTo( PowerUnits.AE, amt ), Actionable.MODULATE ) ); } - protected double funnelPowerIntoStorage(double AEUnits, Actionable mode) + protected double funnelPowerIntoStorage( double AEUnits, Actionable mode ) { return this.injectAEPower( AEUnits, mode ); } @Override - final public double injectAEPower(double amt, Actionable mode) + final public double injectAEPower( double amt, Actionable mode ) { - if ( amt < 0.000001 ) + if( amt < 0.000001 ) return 0; - if ( mode == Actionable.SIMULATE ) + if( mode == Actionable.SIMULATE ) { double fakeBattery = this.internalCurrentPower + amt; - if ( fakeBattery > this.internalMaxPower ) + if( fakeBattery > this.internalMaxPower ) return fakeBattery - this.internalMaxPower; return 0; } else { - if ( this.internalCurrentPower < 0.01 && amt > 0.01 ) + if( this.internalCurrentPower < 0.01 && amt > 0.01 ) this.PowerEvent( PowerEventType.PROVIDE_POWER ); this.internalCurrentPower += amt; - if ( this.internalCurrentPower > this.internalMaxPower ) + if( this.internalCurrentPower > this.internalMaxPower ) { amt = this.internalCurrentPower - this.internalMaxPower; this.internalCurrentPower = this.internalMaxPower; @@ -123,43 +123,11 @@ public abstract class AERootPoweredTile extends AEBaseInvTile implements IAEPowe } } - protected void PowerEvent(PowerEventType x) + protected void PowerEvent( PowerEventType x ) { // nothing. } - protected double extractAEPower(double amt, Actionable mode) - { - if ( mode == Actionable.SIMULATE ) - { - if ( this.internalCurrentPower > amt ) - return amt; - return this.internalCurrentPower; - } - - boolean wasFull = this.internalCurrentPower >= this.internalMaxPower - 0.001; - if ( wasFull && amt > 0.001 ) - { - this.PowerEvent( PowerEventType.REQUEST_POWER ); - } - - if ( this.internalCurrentPower > amt ) - { - this.internalCurrentPower -= amt; - return amt; - } - - amt = this.internalCurrentPower; - this.internalCurrentPower = 0; - return amt; - } - - @Override - final public double extractAEPower(double amt, Actionable mode, PowerMultiplier multiplier) - { - return multiplier.divide( this.extractAEPower( multiplier.multiply( amt ), mode ) ); - } - @Override final public double getAEMaxPower() { @@ -183,4 +151,36 @@ public abstract class AERootPoweredTile extends AEBaseInvTile implements IAEPowe { return this.internalPowerFlow; } + + @Override + final public double extractAEPower( double amt, Actionable mode, PowerMultiplier multiplier ) + { + return multiplier.divide( this.extractAEPower( multiplier.multiply( amt ), mode ) ); + } + + protected double extractAEPower( double amt, Actionable mode ) + { + if( mode == Actionable.SIMULATE ) + { + if( this.internalCurrentPower > amt ) + return amt; + return this.internalCurrentPower; + } + + boolean wasFull = this.internalCurrentPower >= this.internalMaxPower - 0.001; + if( wasFull && amt > 0.001 ) + { + this.PowerEvent( PowerEventType.REQUEST_POWER ); + } + + if( this.internalCurrentPower > amt ) + { + this.internalCurrentPower -= amt; + return amt; + } + + amt = this.internalCurrentPower; + this.internalCurrentPower = 0; + return amt; + } } diff --git a/src/main/java/appeng/tile/powersink/IC2.java b/src/main/java/appeng/tile/powersink/IC2.java index 41cea5d11..a241047b8 100644 --- a/src/main/java/appeng/tile/powersink/IC2.java +++ b/src/main/java/appeng/tile/powersink/IC2.java @@ -18,6 +18,7 @@ package appeng.tile.powersink; + import java.util.EnumSet; import net.minecraft.tileentity.TileEntity; @@ -32,14 +33,15 @@ import appeng.integration.abstraction.IIC2; import appeng.transformer.annotations.Integration.Interface; import appeng.util.Platform; -@Interface(iname = "IC2", iface = "ic2.api.energy.tile.IEnergySink") + +@Interface( iname = "IC2", iface = "ic2.api.energy.tile.IEnergySink" ) public abstract class IC2 extends AERootPoweredTile implements IEnergySink { boolean isInIC2 = false; @Override - final public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + final public boolean acceptsEnergyFrom( TileEntity emitter, ForgeDirection direction ) { return this.getPowerSides().contains( direction ); } @@ -51,7 +53,13 @@ public abstract class IC2 extends AERootPoweredTile implements IEnergySink } @Override - final public double injectEnergy(ForgeDirection directionFrom, double amount, double voltage) + final public int getSinkTier() + { + return Integer.MAX_VALUE; + } + + @Override + final public double injectEnergy( ForgeDirection directionFrom, double amount, double voltage ) { // just store the excess in the current block, if I return the waste, // IC2 will just disintegrate it - Oct 20th 2013 @@ -60,12 +68,6 @@ public abstract class IC2 extends AERootPoweredTile implements IEnergySink return 0; // see above comment. } - @Override - final public int getSinkTier() - { - return Integer.MAX_VALUE; - } - @Override public void invalidate() { @@ -73,6 +75,19 @@ public abstract class IC2 extends AERootPoweredTile implements IEnergySink this.removeFromENet(); } + private void removeFromENet() + { + if( AppEng.instance.isIntegrationEnabled( IntegrationType.IC2 ) ) + { + IIC2 ic2Integration = (IIC2) AppEng.instance.getIntegration( IntegrationType.IC2 ); + if( this.isInIC2 && Platform.isServer() && ic2Integration != null ) + { + ic2Integration.removeFromEnergyNet( this ); + this.isInIC2 = false; + } + } + } + @Override public void onChunkUnload() { @@ -87,20 +102,12 @@ public abstract class IC2 extends AERootPoweredTile implements IEnergySink this.addToENet(); } - @Override - protected void setPowerSides(EnumSet sides) - { - super.setPowerSides( sides ); - this.removeFromENet(); - this.addToENet(); - } - private void addToENet() { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.IC2 ) ) + if( AppEng.instance.isIntegrationEnabled( IntegrationType.IC2 ) ) { IIC2 ic2Integration = (IIC2) AppEng.instance.getIntegration( IntegrationType.IC2 ); - if ( !this.isInIC2 && Platform.isServer() && ic2Integration != null ) + if( !this.isInIC2 && Platform.isServer() && ic2Integration != null ) { ic2Integration.addToEnergyNet( this ); this.isInIC2 = true; @@ -108,17 +115,11 @@ public abstract class IC2 extends AERootPoweredTile implements IEnergySink } } - private void removeFromENet() + @Override + protected void setPowerSides( EnumSet sides ) { - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.IC2 ) ) - { - IIC2 ic2Integration = (IIC2) AppEng.instance.getIntegration( IntegrationType.IC2 ); - if ( this.isInIC2 && Platform.isServer() && ic2Integration != null ) - { - ic2Integration.removeFromEnergyNet( this ); - this.isInIC2 = false; - } - } + super.setPowerSides( sides ); + this.removeFromENet(); + this.addToENet(); } - } diff --git a/src/main/java/appeng/tile/powersink/MekJoules.java b/src/main/java/appeng/tile/powersink/MekJoules.java index a8f03dfde..78f470077 100644 --- a/src/main/java/appeng/tile/powersink/MekJoules.java +++ b/src/main/java/appeng/tile/powersink/MekJoules.java @@ -18,6 +18,7 @@ package appeng.tile.powersink; + import net.minecraftforge.common.util.ForgeDirection; import mekanism.api.energy.IStrictEnergyAcceptor; @@ -25,30 +26,35 @@ import mekanism.api.energy.IStrictEnergyAcceptor; import appeng.api.config.PowerUnits; import appeng.transformer.annotations.Integration.Interface; -@Interface(iname = "Mekanism", iface = "mekanism.api.energy.IStrictEnergyAcceptor") -public abstract class MekJoules extends RedstoneFlux implements IStrictEnergyAcceptor { + +@Interface( iname = "Mekanism", iface = "mekanism.api.energy.IStrictEnergyAcceptor" ) +public abstract class MekJoules extends RedstoneFlux implements IStrictEnergyAcceptor +{ @Override - public double getEnergy() { + public double getEnergy() + { return 0; } @Override - public void setEnergy(double energy) { + public void setEnergy( double energy ) + { double extra = this.injectExternalPower( PowerUnits.MK, energy ); - this.internalCurrentPower += PowerUnits.MK.convertTo(PowerUnits.AE, extra ); + this.internalCurrentPower += PowerUnits.MK.convertTo( PowerUnits.AE, extra ); } @Override - public double getMaxEnergy() { + public double getMaxEnergy() + { return this.getExternalPowerDemand( PowerUnits.MK, 100000 ); } @Override - public double transferEnergyToAcceptor(ForgeDirection side, double amount) + public double transferEnergyToAcceptor( ForgeDirection side, double amount ) { double demand = this.getExternalPowerDemand( PowerUnits.MK, Double.MAX_VALUE ); - if ( amount > demand ) + if( amount > demand ) amount = demand; double overflow = this.injectExternalPower( PowerUnits.MK, amount ); @@ -56,8 +62,8 @@ public abstract class MekJoules extends RedstoneFlux implements IStrictEnergyAcc } @Override - public boolean canReceiveEnergy(ForgeDirection side) { - return this.getPowerSides().contains(side); + public boolean canReceiveEnergy( ForgeDirection side ) + { + return this.getPowerSides().contains( side ); } - } diff --git a/src/main/java/appeng/tile/powersink/RedstoneFlux.java b/src/main/java/appeng/tile/powersink/RedstoneFlux.java index c6c97a1a1..4e18dcfdf 100644 --- a/src/main/java/appeng/tile/powersink/RedstoneFlux.java +++ b/src/main/java/appeng/tile/powersink/RedstoneFlux.java @@ -33,10 +33,10 @@ public abstract class RedstoneFlux extends RotaryCraft implements IEnergyReceive @Override final public int receiveEnergy( ForgeDirection from, int maxReceive, boolean simulate ) { - final int networkRFDemand = ( int ) Math.floor( this.getExternalPowerDemand( PowerUnits.RF, maxReceive ) ); + final int networkRFDemand = (int) Math.floor( this.getExternalPowerDemand( PowerUnits.RF, maxReceive ) ); final int usedRF = Math.min( maxReceive, networkRFDemand ); - if ( !simulate ) + if( !simulate ) { this.injectExternalPower( PowerUnits.RF, usedRF ); } @@ -47,13 +47,13 @@ public abstract class RedstoneFlux extends RotaryCraft implements IEnergyReceive @Override final public int getEnergyStored( ForgeDirection from ) { - return ( int ) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.getAECurrentPower() ) ); + return (int) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.getAECurrentPower() ) ); } @Override final public int getMaxEnergyStored( ForgeDirection from ) { - return ( int ) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.getAEMaxPower() ) ); + return (int) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.getAEMaxPower() ) ); } @Override diff --git a/src/main/java/appeng/tile/powersink/RotaryCraft.java b/src/main/java/appeng/tile/powersink/RotaryCraft.java index d52557ac9..55dc7ac82 100644 --- a/src/main/java/appeng/tile/powersink/RotaryCraft.java +++ b/src/main/java/appeng/tile/powersink/RotaryCraft.java @@ -18,6 +18,7 @@ package appeng.tile.powersink; + import net.minecraftforge.common.util.ForgeDirection; import Reika.RotaryCraft.API.Power.ShaftPowerReceiver; @@ -29,7 +30,8 @@ import appeng.transformer.annotations.Integration.Interface; import appeng.transformer.annotations.Integration.Method; import appeng.util.Platform; -@Interface(iname = "RotaryCraft", iface = "Reika.RotaryCraft.API.Power.ShaftPowerReceiver") + +@Interface( iname = "RotaryCraft", iface = "Reika.RotaryCraft.API.Power.ShaftPowerReceiver" ) public abstract class RotaryCraft extends IC2 implements ShaftPowerReceiver { @@ -38,11 +40,11 @@ public abstract class RotaryCraft extends IC2 implements ShaftPowerReceiver private long power = 0; private int alpha = 0; - @TileEvent(TileEventType.TICK) - @Method(iname = "RotaryCraft") + @TileEvent( TileEventType.TICK ) + @Method( iname = "RotaryCraft" ) public void Tick_RotaryCraft() { - if ( this.worldObj != null && !this.worldObj.isRemote && this.power > 0 ) + if( this.worldObj != null && !this.worldObj.isRemote && this.power > 0 ) this.injectExternalPower( PowerUnits.WA, this.power ); } @@ -77,58 +79,20 @@ public abstract class RotaryCraft extends IC2 implements ShaftPowerReceiver } @Override - final public void setIORenderAlpha(int io) + final public void setIORenderAlpha( int io ) { this.alpha = io; } @Override - final public void setOmega(int o) + final public void setPower( long p ) { - this.omega = o; - } - - @Override - final public void setTorque(int t) - { - this.torque = t; - } - - @Override - final public void setPower(long p) - { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; this.power = p; } - final public boolean canReadFromBlock(int x, int y, int z) - { - ForgeDirection side = ForgeDirection.UNKNOWN; - - if ( x == this.xCoord - 1 ) - side = ForgeDirection.WEST; - else if ( x == this.xCoord + 1 ) - side = ForgeDirection.EAST; - else if ( z == this.zCoord - 1 ) - side = ForgeDirection.NORTH; - else if ( z == this.zCoord + 1 ) - side = ForgeDirection.SOUTH; - else if ( y == this.yCoord - 1 ) - side = ForgeDirection.DOWN; - else if ( y == this.yCoord + 1 ) - side = ForgeDirection.UP; - - return this.getPowerSides().contains( side ); - } - - @Override - final public boolean isReceiving() - { - return true; - } - @Override final public void noInputMachine() { @@ -138,15 +102,52 @@ public abstract class RotaryCraft extends IC2 implements ShaftPowerReceiver } @Override - final public boolean canReadFrom(ForgeDirection side) + final public void setTorque( int t ) + { + this.torque = t; + } + + @Override + final public void setOmega( int o ) + { + this.omega = o; + } + + final public boolean canReadFromBlock( int x, int y, int z ) + { + ForgeDirection side = ForgeDirection.UNKNOWN; + + if( x == this.xCoord - 1 ) + side = ForgeDirection.WEST; + else if( x == this.xCoord + 1 ) + side = ForgeDirection.EAST; + else if( z == this.zCoord - 1 ) + side = ForgeDirection.NORTH; + else if( z == this.zCoord + 1 ) + side = ForgeDirection.SOUTH; + else if( y == this.yCoord - 1 ) + side = ForgeDirection.DOWN; + else if( y == this.yCoord + 1 ) + side = ForgeDirection.UP; + + return this.getPowerSides().contains( side ); + } + + @Override + final public boolean canReadFrom( ForgeDirection side ) { return this.getPowerSides().contains( side ); } @Override - final public int getMinTorque(int available) + final public boolean isReceiving() + { + return true; + } + + @Override + final public int getMinTorque( int available ) { return 0; } - } diff --git a/src/main/java/appeng/tile/qnb/TileQuantumBridge.java b/src/main/java/appeng/tile/qnb/TileQuantumBridge.java index f6cbfbc35..f49a52d59 100644 --- a/src/main/java/appeng/tile/qnb/TileQuantumBridge.java +++ b/src/main/java/appeng/tile/qnb/TileQuantumBridge.java @@ -56,7 +56,7 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock { private static final IBlockDefinition RING_DEFINITION = AEApi.instance().definitions().blocks().quantumRing(); public final byte corner = 16; - final int[] sidesRing = new int[] { }; + final int[] sidesRing = new int[] {}; final int[] sidesLink = new int[] { 0 }; final AppEngInternalInventory internalInventory = new AppEngInternalInventory( this, 1 ); final byte hasSingularity = 32; @@ -79,10 +79,10 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock @TileEvent( TileEventType.TICK ) public void onTickEvent() { - if ( this.updateStatus ) + if( this.updateStatus ) { this.updateStatus = false; - if ( this.cluster != null ) + if( this.cluster != null ) this.cluster.updateStatus( true ); this.markForUpdate(); } @@ -93,10 +93,10 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock { int out = this.constructed; - if ( this.getStackInSlot( 0 ) != null && this.constructed != -1 ) + if( this.getStackInSlot( 0 ) != null && this.constructed != -1 ) out |= this.hasSingularity; - if ( this.gridProxy.isActive() && this.constructed != -1 ) + if( this.gridProxy.isActive() && this.constructed != -1 ) out |= this.powered; data.writeByte( (byte) out ); @@ -120,21 +120,21 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock @Override public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) { - if ( this.cluster != null ) + if( this.cluster != null ) this.cluster.updateStatus( true ); } @Override public int[] getAccessibleSlotsBySide( ForgeDirection side ) { - if ( this.isCenter() ) + if( this.isCenter() ) return this.sidesLink; return this.sidesRing; } public boolean isCenter() { - for ( Block link : AEApi.instance().definitions().blocks().quantumLink().maybeBlock().asSet() ) + for( Block link : AEApi.instance().definitions().blocks().quantumLink().maybeBlock().asSet() ) { return this.getBlockType() == link; } @@ -148,6 +148,13 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock this.updateStatus = true; } + @Override + public void onChunkUnload() + { + this.disconnect( false ); + super.onChunkUnload(); + } + @Override public void onReady() { @@ -159,7 +166,7 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock final boolean isPresent = maybeLinkBlock.isPresent() && maybeLinkStack.isPresent(); - if ( isPresent && this.getBlockType() == maybeLinkBlock.get() ) + if( isPresent && this.getBlockType() == maybeLinkBlock.get() ) { final ItemStack linkStack = maybeLinkStack.get(); @@ -167,13 +174,6 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock } } - @Override - public void onChunkUnload() - { - this.disconnect( false ); - super.onChunkUnload(); - } - @Override public void invalidate() { @@ -184,9 +184,9 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock @Override public void disconnect( boolean affectWorld ) { - if ( this.cluster != null ) + if( this.cluster != null ) { - if ( !affectWorld ) + if( !affectWorld ) this.cluster.updateStatus = false; this.cluster.destroy(); @@ -194,7 +194,7 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock this.cluster = null; - if ( affectWorld ) + if( affectWorld ) this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); } @@ -214,15 +214,15 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock { this.cluster = c; - if ( affectWorld ) + if( affectWorld ) { - if ( this.constructed != flags ) + if( this.constructed != flags ) { this.constructed = flags; this.markForUpdate(); } - if ( this.isCorner() || this.isCenter() ) + if( this.isCorner() || this.isCenter() ) { this.gridProxy.setValidSides( this.getConnections() ); } @@ -240,10 +240,10 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock { EnumSet set = EnumSet.noneOf( ForgeDirection.class ); - for ( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) + for( ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) { TileEntity te = this.worldObj.getTileEntity( this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ ); - if ( te instanceof TileQuantumBridge ) + if( te instanceof TileQuantumBridge ) set.add( d ); } @@ -253,10 +253,10 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock public long getQEFrequency() { ItemStack is = this.internalInventory.getStackInSlot( 0 ); - if ( is != null ) + if( is != null ) { NBTTagCompound c = is.getTagCompound(); - if ( c != null ) + if( c != null ) return c.getLong( "freq" ); } return 0; @@ -264,14 +264,14 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock public boolean isPowered() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return ( this.constructed & this.powered ) == this.powered && this.constructed != -1; try { return this.gridProxy.getEnergy().isNetworkPowered(); } - catch ( GridAccessException e ) + catch( GridAccessException e ) { // :P } @@ -303,14 +303,14 @@ public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock public boolean hasQES() { - if ( this.constructed == -1 ) + if( this.constructed == -1 ) return false; return ( this.constructed & this.hasSingularity ) == this.hasSingularity; } public void breakCluster() { - if ( this.cluster != null ) + if( this.cluster != null ) this.cluster.destroy(); } } diff --git a/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java b/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java index 266132d63..4925e0dcb 100644 --- a/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java +++ b/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java @@ -18,6 +18,7 @@ package appeng.tile.spatial; + import java.util.concurrent.Callable; import net.minecraft.inventory.IInventory; @@ -47,6 +48,7 @@ import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.InvOperation; import appeng.util.Platform; + public class TileSpatialIOPort extends AENetworkInvTile implements Callable { @@ -54,60 +56,71 @@ public class TileSpatialIOPort extends AENetworkInvTile implements Callable final AppEngInternalInventory inv = new AppEngInternalInventory( this, 2 ); YesNo lastRedstoneState = YesNo.UNDECIDED; - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileSpatialIOPort(NBTTagCompound data) + public TileSpatialIOPort() + { + this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); + } + + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileSpatialIOPort( NBTTagCompound data ) { data.setInteger( "lastRedstoneState", this.lastRedstoneState.ordinal() ); } - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileSpatialIOPort(NBTTagCompound data) + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileSpatialIOPort( NBTTagCompound data ) { - if ( data.hasKey( "lastRedstoneState" ) ) + if( data.hasKey( "lastRedstoneState" ) ) this.lastRedstoneState = YesNo.values()[data.getInteger( "lastRedstoneState" )]; } - public TileSpatialIOPort() { - this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); - } - - public void updateRedstoneState() - { - YesNo currentState = this.worldObj.isBlockIndirectlyGettingPowered( this.xCoord, this.yCoord, this.zCoord ) ? YesNo.YES : YesNo.NO; - if ( this.lastRedstoneState != currentState ) - { - this.lastRedstoneState = currentState; - if ( this.lastRedstoneState == YesNo.YES ) - this.triggerTransition(); - } - } - public boolean getRedstoneState() { - if ( this.lastRedstoneState == YesNo.UNDECIDED ) + if( this.lastRedstoneState == YesNo.UNDECIDED ) this.updateRedstoneState(); return this.lastRedstoneState == YesNo.YES; } + public void updateRedstoneState() + { + YesNo currentState = this.worldObj.isBlockIndirectlyGettingPowered( this.xCoord, this.yCoord, this.zCoord ) ? YesNo.YES : YesNo.NO; + if( this.lastRedstoneState != currentState ) + { + this.lastRedstoneState = currentState; + if( this.lastRedstoneState == YesNo.YES ) + this.triggerTransition(); + } + } + private void triggerTransition() { - if ( Platform.isServer() ) + if( Platform.isServer() ) { ItemStack cell = this.getStackInSlot( 0 ); - if ( this.isSpatialCell( cell ) ) + if( this.isSpatialCell( cell ) ) { TickHandler.INSTANCE.addCallable( null, this );// this needs to be cross world synced. } } } + private boolean isSpatialCell( ItemStack cell ) + { + if( cell != null && cell.getItem() instanceof ISpatialStorageCell ) + { + ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); + return sc != null && sc.isSpatialStorage( cell ); + } + return false; + } + @Override public Object call() throws Exception { ItemStack cell = this.getStackInSlot( 0 ); - if ( this.isSpatialCell( cell ) && this.getStackInSlot( 1 ) == null ) + if( this.isSpatialCell( cell ) && this.getStackInSlot( 1 ) == null ) { IGrid gi = this.gridProxy.getGrid(); IEnergyGrid energy = this.gridProxy.getEnergy(); @@ -115,17 +128,17 @@ public class TileSpatialIOPort extends AENetworkInvTile implements Callable ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); SpatialPylonCache spc = gi.getCache( ISpatialCache.class ); - if ( spc.hasRegion() && spc.isValidRegion() ) + if( spc.hasRegion() && spc.isValidRegion() ) { double req = spc.requiredPower(); double pr = energy.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - if ( Math.abs( pr - req ) < req * 0.001 ) + if( Math.abs( pr - req ) < req * 0.001 ) { MENetworkEvent res = gi.postEvent( new MENetworkSpatialEvent( this, req ) ); - if ( !res.isCanceled() ) + if( !res.isCanceled() ) { TransitionResult tr = sc.doSpatialTransition( cell, this.worldObj, spc.getMin(), spc.getMax(), true ); - if ( tr.success ) + if( tr.success ) { energy.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.CONFIG ); this.setInventorySlotContents( 0, null ); @@ -140,7 +153,7 @@ public class TileSpatialIOPort extends AENetworkInvTile implements Callable } @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.SMART; } @@ -158,43 +171,32 @@ public class TileSpatialIOPort extends AENetworkInvTile implements Callable } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { - return (i == 0 && this.isSpatialCell( itemstack )); - } - - private boolean isSpatialCell(ItemStack cell) - { - if ( cell != null && cell.getItem() instanceof ISpatialStorageCell ) - { - ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); - return sc != null && sc.isSpatialStorage( cell ); - } - return false; + return ( i == 0 && this.isSpatialCell( itemstack ) ); } @Override - public boolean canInsertItem(int slotIndex, ItemStack insertingItem, int side ) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) + { + + } + + @Override + public boolean canInsertItem( int slotIndex, ItemStack insertingItem, int side ) { return this.isItemValidForSlot( slotIndex, insertingItem ); } @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side ) + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) { return slotIndex == 1; } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) - { - - } - - @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) + public int[] getAccessibleSlotsBySide( ForgeDirection side ) { return this.sides; } - } diff --git a/src/main/java/appeng/tile/spatial/TileSpatialPylon.java b/src/main/java/appeng/tile/spatial/TileSpatialPylon.java index 67fb1cbf7..35f276ed3 100644 --- a/src/main/java/appeng/tile/spatial/TileSpatialPylon.java +++ b/src/main/java/appeng/tile/spatial/TileSpatialPylon.java @@ -18,6 +18,7 @@ package appeng.tile.spatial; + import java.util.EnumSet; import io.netty.buffer.ByteBuf; @@ -38,6 +39,7 @@ import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.tile.grid.AENetworkTile; + public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock { @@ -52,13 +54,18 @@ public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock public final int DISPLAY_ENABLED = 0x10; public final int DISPLAY_POWERED_ENABLED = 0x20; public final int NET_STATUS = 0x10 + 0x20; - + final SpatialPylonCalculator calc = new SpatialPylonCalculator( this ); int displayBits = 0; SpatialPylonCluster cluster; - final SpatialPylonCalculator calc = new SpatialPylonCalculator( this ); - boolean didHaveLight = false; + public TileSpatialPylon() + { + this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL, GridFlags.MULTIBLOCK ); + this.gridProxy.setIdlePowerUsage( 0.5 ); + this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); + } + @Override protected AENetworkProxy createProxy() { @@ -66,29 +73,10 @@ public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock } @Override - public boolean canBeRotated() + public void onChunkUnload() { - return false; - } - - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileSpatialPylon(ByteBuf data) - { - int old = this.displayBits; - this.displayBits = data.readByte(); - return old != this.displayBits; - } - - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileSpatialPylon(ByteBuf data) - { - data.writeByte( this.displayBits ); - } - - public TileSpatialPylon() { - this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL, GridFlags.MULTIBLOCK ); - this.gridProxy.setIdlePowerUsage( 0.5 ); - this.gridProxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); + this.disconnect( false ); + super.onChunkUnload(); } @Override @@ -98,40 +86,6 @@ public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock this.onNeighborBlockChange(); } - @Override - public void markForUpdate() - { - super.markForUpdate(); - boolean hasLight = this.getLightValue() > 0; - if ( hasLight != this.didHaveLight ) - { - this.didHaveLight = hasLight; - this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); - // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); - } - } - - public int getLightValue() - { - if ( (this.displayBits & this.DISPLAY_POWERED_ENABLED) == this.DISPLAY_POWERED_ENABLED ) - { - return 8; - } - return 0; - } - - @MENetworkEventSubscribe - public void powerRender(MENetworkPowerStatusChange c) - { - this.recalculateDisplay(); - } - - @MENetworkEventSubscribe - public void activeRender(MENetworkChannelsChanged c) - { - this.recalculateDisplay(); - } - @Override public void invalidate() { @@ -139,100 +93,145 @@ public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock super.invalidate(); } - @Override - public void onChunkUnload() - { - this.disconnect( false ); - super.onChunkUnload(); - } - public void onNeighborBlockChange() { this.calc.calculateMultiblock( this.worldObj, this.getLocation() ); } @Override - public SpatialPylonCluster getCluster() + public void disconnect( boolean b ) { - return this.cluster; - } - - public void recalculateDisplay() - { - int oldBits = this.displayBits; - - this.displayBits = 0; - - if ( this.cluster != null ) - { - if ( this.cluster.min.equals( this.getLocation() ) ) - this.displayBits = this.DISPLAY_END_MIN; - else if ( this.cluster.max.equals( this.getLocation() ) ) - this.displayBits = this.DISPLAY_END_MAX; - else - this.displayBits = this.DISPLAY_MIDDLE; - - switch (this.cluster.currentAxis) - { - case X: - this.displayBits |= this.DISPLAY_X; - break; - case Y: - this.displayBits |= this.DISPLAY_Y; - break; - case Z: - this.displayBits |= this.DISPLAY_Z; - break; - default: - this.displayBits = 0; - break; - } - - try - { - if ( this.gridProxy.getEnergy().isNetworkPowered() ) - this.displayBits |= this.DISPLAY_POWERED_ENABLED; - - if ( this.cluster.isValid && this.gridProxy.isActive() ) - this.displayBits |= this.DISPLAY_ENABLED; - } - catch (GridAccessException e) - { - // nothing? - } - - } - - if ( oldBits != this.displayBits ) - this.markForUpdate(); - } - - public void updateStatus(SpatialPylonCluster c) - { - this.cluster = c; - this.gridProxy.setValidSides( c == null ? EnumSet.noneOf( ForgeDirection.class ) : EnumSet.allOf( ForgeDirection.class ) ); - this.recalculateDisplay(); - } - - @Override - public void disconnect(boolean b) - { - if ( this.cluster != null ) + if( this.cluster != null ) { this.cluster.destroy(); this.updateStatus( null ); } } + @Override + public SpatialPylonCluster getCluster() + { + return this.cluster; + } + @Override public boolean isValid() { return true; } + public void updateStatus( SpatialPylonCluster c ) + { + this.cluster = c; + this.gridProxy.setValidSides( c == null ? EnumSet.noneOf( ForgeDirection.class ) : EnumSet.allOf( ForgeDirection.class ) ); + this.recalculateDisplay(); + } + + public void recalculateDisplay() + { + int oldBits = this.displayBits; + + this.displayBits = 0; + + if( this.cluster != null ) + { + if( this.cluster.min.equals( this.getLocation() ) ) + this.displayBits = this.DISPLAY_END_MIN; + else if( this.cluster.max.equals( this.getLocation() ) ) + this.displayBits = this.DISPLAY_END_MAX; + else + this.displayBits = this.DISPLAY_MIDDLE; + + switch( this.cluster.currentAxis ) + { + case X: + this.displayBits |= this.DISPLAY_X; + break; + case Y: + this.displayBits |= this.DISPLAY_Y; + break; + case Z: + this.displayBits |= this.DISPLAY_Z; + break; + default: + this.displayBits = 0; + break; + } + + try + { + if( this.gridProxy.getEnergy().isNetworkPowered() ) + this.displayBits |= this.DISPLAY_POWERED_ENABLED; + + if( this.cluster.isValid && this.gridProxy.isActive() ) + this.displayBits |= this.DISPLAY_ENABLED; + } + catch( GridAccessException e ) + { + // nothing? + } + } + + if( oldBits != this.displayBits ) + this.markForUpdate(); + } + + @Override + public void markForUpdate() + { + super.markForUpdate(); + boolean hasLight = this.getLightValue() > 0; + if( hasLight != this.didHaveLight ) + { + this.didHaveLight = hasLight; + this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); + // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); + } + } + + @Override + public boolean canBeRotated() + { + return false; + } + + public int getLightValue() + { + if( ( this.displayBits & this.DISPLAY_POWERED_ENABLED ) == this.DISPLAY_POWERED_ENABLED ) + { + return 8; + } + return 0; + } + + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileSpatialPylon( ByteBuf data ) + { + int old = this.displayBits; + this.displayBits = data.readByte(); + return old != this.displayBits; + } + + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileSpatialPylon( ByteBuf data ) + { + data.writeByte( this.displayBits ); + } + + @MENetworkEventSubscribe + public void powerRender( MENetworkPowerStatusChange c ) + { + this.recalculateDisplay(); + } + + @MENetworkEventSubscribe + public void activeRender( MENetworkChannelsChanged c ) + { + this.recalculateDisplay(); + } + public int getDisplayBits() { return this.displayBits; } - } diff --git a/src/main/java/appeng/tile/storage/TileChest.java b/src/main/java/appeng/tile/storage/TileChest.java index 6c886f60d..72bdb08d9 100644 --- a/src/main/java/appeng/tile/storage/TileChest.java +++ b/src/main/java/appeng/tile/storage/TileChest.java @@ -91,193 +91,27 @@ import appeng.util.IConfigManagerHost; import appeng.util.Platform; import appeng.util.item.AEFluidStack; + public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHandler, ITerminalHost, IPriorityHost, IConfigManagerHost, IColorableTile { - static private class ChestNoHandler extends Exception - { - - private static final long serialVersionUID = 7995805326136526631L; - - } - static final ChestNoHandler NO_HANDLER = new ChestNoHandler(); - static final int[] SIDES = new int[] { 0 }; static final int[] FRONT = new int[] { 1 }; - static final int[] NO_SLOTS = new int[] { }; - + static final int[] NO_SLOTS = new int[] {}; final AppEngInternalInventory inv = new AppEngInternalInventory( this, 2 ); final BaseActionSource mySrc = new MachineSource( this ); final IConfigManager config = new ConfigManager( this ); - ItemStack storageType; long lastStateChange = 0; int priority = 0; int state = 0; boolean wasActive = false; - AEColor paintedColor = AEColor.Transparent; - - private void recalculateDisplay() - { - int oldState = this.state; - - for (int x = 0; x < this.getCellCount(); x++) - this.state |= (this.getCellStatus( x ) << (3 * x)); - - if ( this.isPowered() ) - this.state |= 0x40; - else - this.state &= ~0x40; - - boolean currentActive = this.gridProxy.isActive(); - if ( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch (GridAccessException e) - { - // :P - } - } - - if ( oldState != this.state ) - this.markForUpdate(); - } - - @Override - protected void PowerEvent(PowerEventType x) - { - if ( x == PowerEventType.REQUEST_POWER ) - { - try - { - this.gridProxy.getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - catch (GridAccessException e) - { - // :( - } - } - else - this.recalculateDisplay(); - } - - @TileEvent(TileEventType.TICK) - public void Tick_TileChest() - { - if ( this.worldObj.isRemote ) - return; - - double idleUsage = this.gridProxy.getIdlePowerUsage(); - - try - { - if ( !this.gridProxy.getEnergy().isNetworkPowered() ) - { - double powerUsed = this.extractAEPower( idleUsage, Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain - if ( powerUsed + 0.1 >= idleUsage != (this.state & 0x40) > 0 ) - this.recalculateDisplay(); - } - } - catch (GridAccessException e) - { - double powerUsed = this.extractAEPower( this.gridProxy.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain - if ( powerUsed + 0.1 >= idleUsage != (this.state & 0x40) > 0 ) - this.recalculateDisplay(); - } - - if ( this.inv.getStackInSlot( 0 ) != null ) - { - this.tryToStoreContents(); - } - } - - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileChest(ByteBuf data) - { - if ( this.worldObj.getTotalWorldTime() - this.lastStateChange > 8 ) - this.state = 0; - else - this.state &= 0x24924924; // just keep the blinks... - - for (int x = 0; x < this.getCellCount(); x++) - this.state |= (this.getCellStatus( x ) << (3 * x)); - - if ( this.isPowered() ) - this.state |= 0x40; - else - this.state &= ~0x40; - - data.writeByte( this.state ); - data.writeByte( this.paintedColor.ordinal() ); - - ItemStack is = this.inv.getStackInSlot( 1 ); - - if ( is == null ) - { - data.writeInt( 0 ); - } - else - { - data.writeInt( (is.getItemDamage() << Platform.DEF_OFFSET) | Item.getIdFromItem( is.getItem() ) ); - } - } - - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileChest(ByteBuf data) - { - int oldState = this.state; - ItemStack oldType = this.storageType; - - this.state = data.readByte(); - AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; - - int item = data.readInt(); - - if ( item == 0 ) - this.storageType = null; - else - this.storageType = new ItemStack( Item.getItemById( item & 0xffff ), 1, item >> Platform.DEF_OFFSET ); - - this.lastStateChange = this.worldObj.getTotalWorldTime(); - - return oldPaintedColor != this.paintedColor || (this.state & 0xDB6DB6DB) != (oldState & 0xDB6DB6DB) || !Platform.isSameItemPrecise( oldType, this.storageType ); - } - - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileChest(NBTTagCompound data) - { - this.config.readFromNBT( data ); - this.priority = data.getInteger( "priority" ); - if ( data.hasKey( "paintedColor" ) ) - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } - - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileChest(NBTTagCompound data) - { - this.config.writeToNBT( data ); - data.setInteger( "priority", this.priority ); - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); - } - - @MENetworkEventSubscribe - public void powerRender(MENetworkPowerStatusChange c) - { - this.recalculateDisplay(); - } - - @MENetworkEventSubscribe - public void channelRender(MENetworkChannelsChanged c) - { - this.recalculateDisplay(); - } + boolean isCached = false; + private ICellHandler cellHandler; + private MEMonitorHandler itemCell; + private MEMonitorHandler fluidCell; public TileChest() { @@ -291,11 +125,322 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan this.internalPowerFlow = AccessRestriction.WRITE; } - boolean isCached = false; + @Override + protected void PowerEvent( PowerEventType x ) + { + if( x == PowerEventType.REQUEST_POWER ) + { + try + { + this.gridProxy.getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); + } + catch( GridAccessException e ) + { + // :( + } + } + else + this.recalculateDisplay(); + } - private ICellHandler cellHandler; - private MEMonitorHandler itemCell; - private MEMonitorHandler fluidCell; + private void recalculateDisplay() + { + int oldState = this.state; + + for( int x = 0; x < this.getCellCount(); x++ ) + this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); + + if( this.isPowered() ) + this.state |= 0x40; + else + this.state &= ~0x40; + + boolean currentActive = this.gridProxy.isActive(); + if( this.wasActive != currentActive ) + { + this.wasActive = currentActive; + try + { + this.gridProxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); + } + catch( GridAccessException e ) + { + // :P + } + } + + if( oldState != this.state ) + this.markForUpdate(); + } + + @Override + public int getCellCount() + { + return 1; + } + + public IMEInventoryHandler getHandler( StorageChannel channel ) throws ChestNoHandler + { + if( !this.isCached ) + { + this.itemCell = null; + this.fluidCell = null; + + ItemStack is = this.inv.getStackInSlot( 1 ); + if( is != null ) + { + this.isCached = true; + this.cellHandler = AEApi.instance().registries().cell().getHandler( is ); + if( this.cellHandler != null ) + { + double power = 1.0; + + IMEInventoryHandler itemCell = this.cellHandler.getCellInventory( is, this, StorageChannel.ITEMS ); + IMEInventoryHandler fluidCell = this.cellHandler.getCellInventory( is, this, StorageChannel.FLUIDS ); + + if( itemCell != null ) + power += this.cellHandler.cellIdleDrain( is, itemCell ); + else if( fluidCell != null ) + power += this.cellHandler.cellIdleDrain( is, fluidCell ); + + this.gridProxy.setIdlePowerUsage( power ); + + this.itemCell = this.wrap( itemCell ); + this.fluidCell = this.wrap( fluidCell ); + } + } + } + + switch( channel ) + { + case FLUIDS: + if( this.fluidCell == null ) + throw NO_HANDLER; + return this.fluidCell; + case ITEMS: + if( this.itemCell == null ) + throw NO_HANDLER; + return this.itemCell; + default: + } + + return null; + } + + private MEMonitorHandler wrap( IMEInventoryHandler h ) + { + if( h == null ) + return null; + + MEInventoryHandler ih = new MEInventoryHandler( h, h.getChannel() ); + ih.setPriority( this.priority ); + + MEMonitorHandler g = new ChestMonitorHandler( ih ); + g.addListener( new ChestNetNotifier( h.getChannel() ), g ); + + return g; + } + + @Override + public int getCellStatus( int slot ) + { + if( Platform.isClient() ) + return ( this.state >> ( slot * 3 ) ) & 3; + + ItemStack cell = this.inv.getStackInSlot( 1 ); + ICellHandler ch = AEApi.instance().registries().cell().getHandler( cell ); + + if( ch != null ) + { + try + { + IMEInventoryHandler handler = this.getHandler( StorageChannel.ITEMS ); + if( handler instanceof ChestMonitorHandler ) + return ch.getStatusForCell( cell, ( (ChestMonitorHandler) handler ).getInternalHandler() ); + } + catch( ChestNoHandler ignored ) + { + } + + try + { + IMEInventoryHandler handler = this.getHandler( StorageChannel.FLUIDS ); + if( handler instanceof ChestMonitorHandler ) + return ch.getStatusForCell( cell, ( (ChestMonitorHandler) handler ).getInternalHandler() ); + } + catch( ChestNoHandler ignored ) + { + } + } + + return 0; + } + + @Override + public boolean isPowered() + { + if( Platform.isClient() ) + return ( this.state & 0x40 ) == 0x40; + + boolean gridPowered = this.getAECurrentPower() > 64; + + if( !gridPowered ) + { + try + { + gridPowered = this.gridProxy.getEnergy().isNetworkPowered(); + } + catch( GridAccessException ignored ) + { + } + } + + return super.getAECurrentPower() > 1 || gridPowered; + } + + @Override + public boolean isCellBlinking( int slot ) + { + long now = this.worldObj.getTotalWorldTime(); + if( now - this.lastStateChange > 8 ) + return false; + + return ( ( this.state >> ( slot * 3 + 2 ) ) & 0x01 ) == 0x01; + } + + @Override + protected double extractAEPower( double amt, Actionable mode ) + { + double stash = 0.0; + + IEnergyGrid eg; + try + { + eg = this.gridProxy.getEnergy(); + stash = eg.extractAEPower( amt, mode, PowerMultiplier.ONE ); + if( stash >= amt ) + return stash; + } + catch( GridAccessException e ) + { + // no grid :( + } + + // local battery! + return super.extractAEPower( amt - stash, mode ) + stash; + } + + @TileEvent( TileEventType.TICK ) + public void Tick_TileChest() + { + if( this.worldObj.isRemote ) + return; + + double idleUsage = this.gridProxy.getIdlePowerUsage(); + + try + { + if( !this.gridProxy.getEnergy().isNetworkPowered() ) + { + double powerUsed = this.extractAEPower( idleUsage, Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain + if( powerUsed + 0.1 >= idleUsage != ( this.state & 0x40 ) > 0 ) + this.recalculateDisplay(); + } + } + catch( GridAccessException e ) + { + double powerUsed = this.extractAEPower( this.gridProxy.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain + if( powerUsed + 0.1 >= idleUsage != ( this.state & 0x40 ) > 0 ) + this.recalculateDisplay(); + } + + if( this.inv.getStackInSlot( 0 ) != null ) + { + this.tryToStoreContents(); + } + } + + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileChest( ByteBuf data ) + { + if( this.worldObj.getTotalWorldTime() - this.lastStateChange > 8 ) + this.state = 0; + else + this.state &= 0x24924924; // just keep the blinks... + + for( int x = 0; x < this.getCellCount(); x++ ) + this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); + + if( this.isPowered() ) + this.state |= 0x40; + else + this.state &= ~0x40; + + data.writeByte( this.state ); + data.writeByte( this.paintedColor.ordinal() ); + + ItemStack is = this.inv.getStackInSlot( 1 ); + + if( is == null ) + { + data.writeInt( 0 ); + } + else + { + data.writeInt( ( is.getItemDamage() << Platform.DEF_OFFSET ) | Item.getIdFromItem( is.getItem() ) ); + } + } + + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileChest( ByteBuf data ) + { + int oldState = this.state; + ItemStack oldType = this.storageType; + + this.state = data.readByte(); + AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; + + int item = data.readInt(); + + if( item == 0 ) + this.storageType = null; + else + this.storageType = new ItemStack( Item.getItemById( item & 0xffff ), 1, item >> Platform.DEF_OFFSET ); + + this.lastStateChange = this.worldObj.getTotalWorldTime(); + + return oldPaintedColor != this.paintedColor || ( this.state & 0xDB6DB6DB ) != ( oldState & 0xDB6DB6DB ) || !Platform.isSameItemPrecise( oldType, this.storageType ); + } + + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileChest( NBTTagCompound data ) + { + this.config.readFromNBT( data ); + this.priority = data.getInteger( "priority" ); + if( data.hasKey( "paintedColor" ) ) + this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; + } + + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileChest( NBTTagCompound data ) + { + this.config.writeToNBT( data ); + data.setInteger( "priority", this.priority ); + data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); + } + + @MENetworkEventSubscribe + public void powerRender( MENetworkPowerStatusChange c ) + { + this.recalculateDisplay(); + } + + @MENetworkEventSubscribe + public void channelRender( MENetworkChannelsChanged c ) + { + this.recalculateDisplay(); + } @Override public IMEMonitor getItemInventory() @@ -309,180 +454,6 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan return this.fluidCell; } - class ChestNetNotifier> implements IMEMonitorHandlerReceiver - { - - final StorageChannel chan; - - public ChestNetNotifier(StorageChannel chan) - { - this.chan = chan; - } - - @Override - public void postChange(IBaseMonitor monitor, Iterable change, BaseActionSource source) - { - if ( source == TileChest.this.mySrc || (source instanceof PlayerSource && ((PlayerSource) source).via == TileChest.this) ) - { - try - { - if ( TileChest.this.gridProxy.isActive() ) - TileChest.this.gridProxy.getStorage().postAlterationOfStoredItems( this.chan, change, TileChest.this.mySrc ); - } - catch (GridAccessException e) - { - // :( - } - } - - TileChest.this.blinkCell( 0 ); - } - - @Override - public boolean isValid(Object verificationToken) - { - if ( this.chan == StorageChannel.ITEMS ) - return verificationToken == TileChest.this.itemCell; - if ( this.chan == StorageChannel.FLUIDS ) - return verificationToken == TileChest.this.fluidCell; - return false; - } - - @Override - public void onListUpdate() - { - // not used here - } - - } - - class ChestMonitorHandler extends MEMonitorHandler - { - - public ChestMonitorHandler(IMEInventoryHandler t) - { - super( t ); - } - - public IMEInventoryHandler getInternalHandler() - { - IMEInventoryHandler h = this.getHandler(); - if ( h instanceof MEInventoryHandler ) - return (IMEInventoryHandler) ((MEInventoryHandler) h).getInternal(); - return this.getHandler(); - } - - private boolean securityCheck(EntityPlayer player, SecurityPermissions requiredPermission) - { - if ( TileChest.this.getTile() instanceof IActionHost && requiredPermission != null ) - { - boolean requirePower = false; - - IGridNode gn = ((IActionHost) TileChest.this.getTile()).getActionableNode(); - if ( gn != null ) - { - IGrid g = gn.getGrid(); - if ( g != null ) - { - if ( requirePower ) - { - IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if ( !eg.isNetworkPowered() ) - { - return false; - } - } - - ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if ( sg.hasPermission( player, requiredPermission ) ) - return true; - } - } - - return false; - } - return true; - } - - @Override - public T injectItems(T input, Actionable mode, BaseActionSource src) - { - if ( src.isPlayer() && !this.securityCheck(((PlayerSource) src).player, SecurityPermissions.INJECT) ) - return input; - return super.injectItems(input, mode, src); - } - - @Override - public T extractItems(T request, Actionable mode, BaseActionSource src) - { - if ( src.isPlayer() && !this.securityCheck(((PlayerSource) src).player, SecurityPermissions.EXTRACT) ) - return null; - return super.extractItems(request, mode, src); - } - } - - private MEMonitorHandler wrap(IMEInventoryHandler h) - { - if ( h == null ) - return null; - - MEInventoryHandler ih = new MEInventoryHandler( h, h.getChannel() ); - ih.setPriority( this.priority ); - - MEMonitorHandler g = new ChestMonitorHandler( ih ); - g.addListener( new ChestNetNotifier( h.getChannel() ), g ); - - return g; - } - - public IMEInventoryHandler getHandler(StorageChannel channel) throws ChestNoHandler - { - if ( !this.isCached ) - { - this.itemCell = null; - this.fluidCell = null; - - ItemStack is = this.inv.getStackInSlot( 1 ); - if ( is != null ) - { - this.isCached = true; - this.cellHandler = AEApi.instance().registries().cell().getHandler( is ); - if ( this.cellHandler != null ) - { - double power = 1.0; - - IMEInventoryHandler itemCell = this.cellHandler.getCellInventory( is, this, StorageChannel.ITEMS ); - IMEInventoryHandler fluidCell = this.cellHandler.getCellInventory( is, this, StorageChannel.FLUIDS ); - - if ( itemCell != null ) - power += this.cellHandler.cellIdleDrain( is, itemCell ); - else if ( fluidCell != null ) - power += this.cellHandler.cellIdleDrain( is, fluidCell ); - - this.gridProxy.setIdlePowerUsage( power ); - - this.itemCell = this.wrap( itemCell ); - this.fluidCell = this.wrap( fluidCell ); - } - } - } - - switch (channel) - { - case FLUIDS: - if ( this.fluidCell == null ) - throw NO_HANDLER; - return this.fluidCell; - case ITEMS: - if ( this.itemCell == null ) - throw NO_HANDLER; - return this.itemCell; - default: - } - - return null; - } - @Override public IInventory getInternalInventory() { @@ -490,9 +461,16 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) + public void setInventorySlotContents( int i, ItemStack itemstack ) { - if ( slot == 1 ) + this.inv.setInventorySlotContents( i, itemstack ); + this.tryToStoreContents(); + } + + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) + { + if( slot == 1 ) { this.itemCell = null; this.fluidCell = null; @@ -505,13 +483,13 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan IStorageGrid gs = this.gridProxy.getStorage(); Platform.postChanges( gs, removed, added, this.mySrc ); } - catch (GridAccessException ignored) + catch( GridAccessException ignored ) { } // update the neighbors - if ( this.worldObj != null ) + if( this.worldObj != null ) { Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); this.markForUpdate(); @@ -520,47 +498,13 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public boolean canInsertItem( int slotIndex, ItemStack insertingItem, int side ) { - this.inv.setInventorySlotContents( i, itemstack ); - this.tryToStoreContents(); - } - - private void tryToStoreContents() - { - try + if( slotIndex == 1 ) { - if ( this.getStackInSlot( 0 ) != null ) - { - IMEInventory cell = this.getHandler( StorageChannel.ITEMS ); - - IAEItemStack returns = Platform.poweredInsert( this, cell, AEApi.instance().storage().createItemStack( this.inv.getStackInSlot( 0 ) ), this.mySrc ); - - if ( returns == null ) - this.inv.setInventorySlotContents( 0, null ); - else - this.inv.setInventorySlotContents( 0, returns.getItemStack() ); - } - } - catch (ChestNoHandler ignored) - { - } - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack extractedItem, int side ) - { - return slotIndex == 1; - } - - @Override - public boolean canInsertItem(int slotIndex, ItemStack insertingItem, int side ) - { - if ( slotIndex == 1 ) - { - if ( AEApi.instance().registries().cell().getCellInventory( insertingItem, this, StorageChannel.ITEMS ) != null ) + if( AEApi.instance().registries().cell().getCellInventory( insertingItem, this, StorageChannel.ITEMS ) != null ) return true; - if ( AEApi.instance().registries().cell().getCellInventory( insertingItem, this, StorageChannel.FLUIDS ) != null ) + if( AEApi.instance().registries().cell().getCellInventory( insertingItem, this, StorageChannel.FLUIDS ) != null ) return true; } else @@ -571,7 +515,7 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan IAEItemStack returns = cell.injectItems( AEApi.instance().storage().createItemStack( this.inv.getStackInSlot( 0 ) ), Actionable.SIMULATE, this.mySrc ); return returns == null || returns.getStackSize() != insertingItem.stackSize; } - catch (ChestNoHandler ignored) + catch( ChestNoHandler ignored ) { } } @@ -579,19 +523,25 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan } @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) + public boolean canExtractItem( int slotIndex, ItemStack extractedItem, int side ) { - if ( ForgeDirection.SOUTH == side ) + return slotIndex == 1; + } + + @Override + public int[] getAccessibleSlotsBySide( ForgeDirection side ) + { + if( ForgeDirection.SOUTH == side ) return FRONT; - if ( this.isPowered() ) + if( this.isPowered() ) { try { - if ( this.getHandler( StorageChannel.ITEMS ) != null ) + if( this.getHandler( StorageChannel.ITEMS ) != null ) return SIDES; } - catch (ChestNoHandler e) + catch( ChestNoHandler e ) { // nope! } @@ -599,16 +549,37 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan return NO_SLOTS; } - @Override - public List getCellArray(StorageChannel channel) + private void tryToStoreContents() { - if ( this.gridProxy.isActive() ) + try + { + if( this.getStackInSlot( 0 ) != null ) + { + IMEInventory cell = this.getHandler( StorageChannel.ITEMS ); + + IAEItemStack returns = Platform.poweredInsert( this, cell, AEApi.instance().storage().createItemStack( this.inv.getStackInSlot( 0 ) ), this.mySrc ); + + if( returns == null ) + this.inv.setInventorySlotContents( 0, null ); + else + this.inv.setInventorySlotContents( 0, returns.getItemStack() ); + } + } + catch( ChestNoHandler ignored ) + { + } + } + + @Override + public List getCellArray( StorageChannel channel ) + { + if( this.gridProxy.isActive() ) { try { return Collections.singletonList( this.getHandler( channel ) ); } - catch (ChestNoHandler e) + catch( ChestNoHandler e ) { // :P } @@ -623,204 +594,7 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan } @Override - public int getCellCount() - { - return 1; - } - - @Override - public void blinkCell(int slot) - { - long now = this.worldObj.getTotalWorldTime(); - if ( now - this.lastStateChange > 8 ) - this.state = 0; - this.lastStateChange = now; - - this.state |= 1 << (slot * 3 + 2); - - this.recalculateDisplay(); - } - - @Override - public boolean isCellBlinking(int slot) - { - long now = this.worldObj.getTotalWorldTime(); - if ( now - this.lastStateChange > 8 ) - return false; - - return ((this.state >> (slot * 3 + 2)) & 0x01) == 0x01; - } - - @Override - public int getCellStatus(int slot) - { - if ( Platform.isClient() ) - return (this.state >> (slot * 3)) & 3; - - ItemStack cell = this.inv.getStackInSlot( 1 ); - ICellHandler ch = AEApi.instance().registries().cell().getHandler( cell ); - - if ( ch != null ) - { - try - { - IMEInventoryHandler handler = this.getHandler( StorageChannel.ITEMS ); - if ( handler instanceof ChestMonitorHandler ) - return ch.getStatusForCell( cell, ((ChestMonitorHandler) handler).getInternalHandler() ); - } - catch (ChestNoHandler ignored) - { - } - - try - { - IMEInventoryHandler handler = this.getHandler( StorageChannel.FLUIDS ); - if ( handler instanceof ChestMonitorHandler ) - return ch.getStatusForCell( cell, ((ChestMonitorHandler) handler).getInternalHandler() ); - } - catch (ChestNoHandler ignored) - { - } - } - - return 0; - } - - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) - { - double req = resource.amount / 500.0; - double available = this.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - if ( available >= req - 0.01 ) - { - try - { - IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - - this.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.CONFIG ); - IAEStack results = h.injectItems( AEFluidStack.create( resource ), doFill ? Actionable.MODULATE : Actionable.SIMULATE, this.mySrc ); - - if ( results == null ) - return resource.amount; - - return resource.amount - (int) results.getStackSize(); - } - catch (ChestNoHandler ignored) - { - } - } - return 0; - } - - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) - { - return null; - } - - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) - { - return null; - } - - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) - { - try - { - IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - return h.canAccept( AEFluidStack.create( new FluidStack( fluid, 1 ) ) ); - } - catch (ChestNoHandler ignored) - { - } - return false; - } - - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) - { - return false; - } - - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) - { - try - { - IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - if ( h.getChannel() == StorageChannel.FLUIDS ) - return new FluidTankInfo[] { new FluidTankInfo( null, 1 ) }; // eh? - } - catch (ChestNoHandler ignored) - { - } - - return null; - } - - @Override - protected double extractAEPower(double amt, Actionable mode) - { - double stash = 0.0; - - IEnergyGrid eg; - try - { - eg = this.gridProxy.getEnergy(); - stash = eg.extractAEPower( amt, mode, PowerMultiplier.ONE ); - if ( stash >= amt ) - return stash; - } - catch (GridAccessException e) - { - // no grid :( - } - - // local battery! - return super.extractAEPower( amt - stash, mode ) + stash; - } - - @Override - public boolean isPowered() - { - if ( Platform.isClient() ) - return (this.state & 0x40) == 0x40; - - boolean gridPowered = this.getAECurrentPower() > 64; - - if ( !gridPowered ) - { - try - { - gridPowered = this.gridProxy.getEnergy().isNetworkPowered(); - } - catch (GridAccessException ignored) - { - } - } - - return super.getAECurrentPower() > 1 || gridPowered; - } - - @Override - public IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src) - { - if ( Platform.canAccess( this.gridProxy, src ) && side != this.getForward() ) - return this; - return null; - } - - public ItemStack getStorageType() - { - if ( this.isPowered() ) - return this.storageType; - return null; - } - - @Override - public void setPriority(int newValue) + public void setPriority( int newValue ) { this.priority = newValue; @@ -832,12 +606,114 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan { this.gridProxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // :P } } + @Override + public void blinkCell( int slot ) + { + long now = this.worldObj.getTotalWorldTime(); + if( now - this.lastStateChange > 8 ) + this.state = 0; + this.lastStateChange = now; + + this.state |= 1 << ( slot * 3 + 2 ); + + this.recalculateDisplay(); + } + + @Override + public int fill( ForgeDirection from, FluidStack resource, boolean doFill ) + { + double req = resource.amount / 500.0; + double available = this.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.CONFIG ); + if( available >= req - 0.01 ) + { + try + { + IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); + + this.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.CONFIG ); + IAEStack results = h.injectItems( AEFluidStack.create( resource ), doFill ? Actionable.MODULATE : Actionable.SIMULATE, this.mySrc ); + + if( results == null ) + return resource.amount; + + return resource.amount - (int) results.getStackSize(); + } + catch( ChestNoHandler ignored ) + { + } + } + return 0; + } + + @Override + public FluidStack drain( ForgeDirection from, FluidStack resource, boolean doDrain ) + { + return null; + } + + @Override + public FluidStack drain( ForgeDirection from, int maxDrain, boolean doDrain ) + { + return null; + } + + @Override + public boolean canFill( ForgeDirection from, Fluid fluid ) + { + try + { + IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); + return h.canAccept( AEFluidStack.create( new FluidStack( fluid, 1 ) ) ); + } + catch( ChestNoHandler ignored ) + { + } + return false; + } + + @Override + public boolean canDrain( ForgeDirection from, Fluid fluid ) + { + return false; + } + + @Override + public FluidTankInfo[] getTankInfo( ForgeDirection from ) + { + try + { + IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); + if( h.getChannel() == StorageChannel.FLUIDS ) + return new FluidTankInfo[] { new FluidTankInfo( null, 1 ) }; // eh? + } + catch( ChestNoHandler ignored ) + { + } + + return null; + } + + @Override + public IStorageMonitorable getMonitorable( ForgeDirection side, BaseActionSource src ) + { + if( Platform.canAccess( this.gridProxy, src ) && side != this.getForward() ) + return this; + return null; + } + + public ItemStack getStorageType() + { + if( this.isPowered() ) + return this.storageType; + return null; + } + @Override public IConfigManager getConfigManager() { @@ -845,24 +721,23 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan } @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) + public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ) { } - public boolean openGui(EntityPlayer p, ICellHandler ch, ItemStack cell, int side) + public boolean openGui( EntityPlayer p, ICellHandler ch, ItemStack cell, int side ) { try { IMEInventoryHandler invHandler = this.getHandler( StorageChannel.ITEMS ); - if ( ch != null && invHandler != null ) + if( ch != null && invHandler != null ) { ch.openChestGui( p, this, ch, invHandler, cell, StorageChannel.ITEMS ); return true; } - } - catch (ChestNoHandler e) + catch( ChestNoHandler e ) { // :P } @@ -870,13 +745,13 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan try { IMEInventoryHandler invHandler = this.getHandler( StorageChannel.FLUIDS ); - if ( ch != null && invHandler != null ) + if( ch != null && invHandler != null ) { ch.openChestGui( p, this, ch, invHandler, cell, StorageChannel.FLUIDS ); return true; } } - catch (ChestNoHandler e) + catch( ChestNoHandler e ) { // :P } @@ -891,9 +766,9 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan } @Override - public boolean recolourBlock(ForgeDirection side, AEColor newPaintedColor, EntityPlayer who) + public boolean recolourBlock( ForgeDirection side, AEColor newPaintedColor, EntityPlayer who ) { - if ( this.paintedColor == newPaintedColor ) + if( this.paintedColor == newPaintedColor ) return false; this.paintedColor = newPaintedColor; @@ -903,8 +778,127 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHan } @Override - public void saveChanges(IMEInventory cellInventory) + public void saveChanges( IMEInventory cellInventory ) { this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); } + + static private class ChestNoHandler extends Exception + { + + private static final long serialVersionUID = 7995805326136526631L; + } + + + class ChestNetNotifier> implements IMEMonitorHandlerReceiver + { + + final StorageChannel chan; + + public ChestNetNotifier( StorageChannel chan ) + { + this.chan = chan; + } + + @Override + public boolean isValid( Object verificationToken ) + { + if( this.chan == StorageChannel.ITEMS ) + return verificationToken == TileChest.this.itemCell; + if( this.chan == StorageChannel.FLUIDS ) + return verificationToken == TileChest.this.fluidCell; + return false; + } + + @Override + public void postChange( IBaseMonitor monitor, Iterable change, BaseActionSource source ) + { + if( source == TileChest.this.mySrc || ( source instanceof PlayerSource && ( (PlayerSource) source ).via == TileChest.this ) ) + { + try + { + if( TileChest.this.gridProxy.isActive() ) + TileChest.this.gridProxy.getStorage().postAlterationOfStoredItems( this.chan, change, TileChest.this.mySrc ); + } + catch( GridAccessException e ) + { + // :( + } + } + + TileChest.this.blinkCell( 0 ); + } + + @Override + public void onListUpdate() + { + // not used here + } + } + + + class ChestMonitorHandler extends MEMonitorHandler + { + + public ChestMonitorHandler( IMEInventoryHandler t ) + { + super( t ); + } + + public IMEInventoryHandler getInternalHandler() + { + IMEInventoryHandler h = this.getHandler(); + if( h instanceof MEInventoryHandler ) + return (IMEInventoryHandler) ( (MEInventoryHandler) h ).getInternal(); + return this.getHandler(); + } + + @Override + public T injectItems( T input, Actionable mode, BaseActionSource src ) + { + if( src.isPlayer() && !this.securityCheck( ( (PlayerSource) src ).player, SecurityPermissions.INJECT ) ) + return input; + return super.injectItems( input, mode, src ); + } + + private boolean securityCheck( EntityPlayer player, SecurityPermissions requiredPermission ) + { + if( TileChest.this.getTile() instanceof IActionHost && requiredPermission != null ) + { + boolean requirePower = false; + + IGridNode gn = ( (IActionHost) TileChest.this.getTile() ).getActionableNode(); + if( gn != null ) + { + IGrid g = gn.getGrid(); + if( g != null ) + { + if( requirePower ) + { + IEnergyGrid eg = g.getCache( IEnergyGrid.class ); + if( !eg.isNetworkPowered() ) + { + return false; + } + } + + ISecurityGrid sg = g.getCache( ISecurityGrid.class ); + if( sg.hasPermission( player, requiredPermission ) ) + return true; + } + } + + return false; + } + return true; + } + + @Override + public T extractItems( T request, Actionable mode, BaseActionSource src ) + { + if( src.isPlayer() && !this.securityCheck( ( (PlayerSource) src ).player, SecurityPermissions.EXTRACT ) ) + return null; + return super.extractItems( request, mode, src ); + } + } } diff --git a/src/main/java/appeng/tile/storage/TileDrive.java b/src/main/java/appeng/tile/storage/TileDrive.java index 8a2a8461f..1d04e6b72 100644 --- a/src/main/java/appeng/tile/storage/TileDrive.java +++ b/src/main/java/appeng/tile/storage/TileDrive.java @@ -18,6 +18,7 @@ package appeng.tile.storage; + import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -57,114 +58,167 @@ import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.InvOperation; import appeng.util.Platform; + public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPriorityHost { final int[] sides = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; final AppEngInternalInventory inv = new AppEngInternalInventory( this, 10 ); - - boolean isCached = false; final ICellHandler[] handlersBySlot = new ICellHandler[10]; final DriveWatcher[] invBySlot = new DriveWatcher[10]; + final BaseActionSource mySrc; + boolean isCached = false; List items = new LinkedList(); List fluids = new LinkedList(); - - final BaseActionSource mySrc; long lastStateChange = 0; int state = 0; int priority = 0; boolean wasActive = false; + public TileDrive() + { + this.mySrc = new MachineSource( this ); + this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); + } + + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileDrive( ByteBuf data ) + { + if( this.worldObj.getTotalWorldTime() - this.lastStateChange > 8 ) + this.state = 0; + else + this.state &= 0x24924924; // just keep the blinks... + + if( this.gridProxy.isActive() ) + this.state |= 0x80000000; + else + this.state &= ~0x80000000; + + for( int x = 0; x < this.getCellCount(); x++ ) + this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); + + data.writeInt( this.state ); + } + + @Override + public int getCellCount() + { + return 10; + } + + @Override + public int getCellStatus( int slot ) + { + if( Platform.isClient() ) + return ( this.state >> ( slot * 3 ) ) & 3; + + ItemStack cell = this.inv.getStackInSlot( 2 ); + ICellHandler ch = this.handlersBySlot[slot]; + + MEInventoryHandler handler = this.invBySlot[slot]; + if( handler == null ) + return 0; + + if( handler.getChannel() == StorageChannel.ITEMS ) + { + if( ch != null ) + return ch.getStatusForCell( cell, handler.getInternal() ); + } + + if( handler.getChannel() == StorageChannel.FLUIDS ) + { + if( ch != null ) + return ch.getStatusForCell( cell, handler.getInternal() ); + } + + return 0; + } + + @Override + public boolean isPowered() + { + if( Platform.isClient() ) + return ( this.state & 0x80000000 ) == 0x80000000; + + return this.gridProxy.isActive(); + } + + @Override + public boolean isCellBlinking( int slot ) + { + long now = this.worldObj.getTotalWorldTime(); + if( now - this.lastStateChange > 8 ) + return false; + + return ( ( this.state >> ( slot * 3 + 2 ) ) & 0x01 ) == 0x01; + } + + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileDrive( ByteBuf data ) + { + int oldState = this.state; + this.state = data.readInt(); + this.lastStateChange = this.worldObj.getTotalWorldTime(); + return ( this.state & 0xDB6DB6DB ) != ( oldState & 0xDB6DB6DB ); + } + + @TileEvent( TileEventType.WORLD_NBT_READ ) + public void readFromNBT_TileDrive( NBTTagCompound data ) + { + this.isCached = false; + this.priority = data.getInteger( "priority" ); + } + + @TileEvent( TileEventType.WORLD_NBT_WRITE ) + public void writeToNBT_TileDrive( NBTTagCompound data ) + { + data.setInteger( "priority", this.priority ); + } + + @MENetworkEventSubscribe + public void powerRender( MENetworkPowerStatusChange c ) + { + this.recalculateDisplay(); + } + private void recalculateDisplay() { int oldState = 0; boolean currentActive = this.gridProxy.isActive(); - if ( currentActive ) + if( currentActive ) this.state |= 0x80000000; else this.state &= ~0x80000000; - if ( this.wasActive != currentActive ) + if( this.wasActive != currentActive ) { this.wasActive = currentActive; try { this.gridProxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // :P } } - for (int x = 0; x < this.getCellCount(); x++) - this.state |= (this.getCellStatus( x ) << (3 * x)); + for( int x = 0; x < this.getCellCount(); x++ ) + this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); - if ( oldState != this.state ) + if( oldState != this.state ) this.markForUpdate(); } - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileDrive(ByteBuf data) - { - if ( this.worldObj.getTotalWorldTime() - this.lastStateChange > 8 ) - this.state = 0; - else - this.state &= 0x24924924; // just keep the blinks... - - if ( this.gridProxy.isActive() ) - this.state |= 0x80000000; - else - this.state &= ~0x80000000; - - for (int x = 0; x < this.getCellCount(); x++) - this.state |= (this.getCellStatus( x ) << (3 * x)); - - data.writeInt( this.state ); - } - - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileDrive(ByteBuf data) - { - int oldState = this.state; - this.state = data.readInt(); - this.lastStateChange = this.worldObj.getTotalWorldTime(); - return (this.state & 0xDB6DB6DB) != (oldState & 0xDB6DB6DB); - } - - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_TileDrive(NBTTagCompound data) - { - this.isCached = false; - this.priority = data.getInteger( "priority" ); - } - - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_TileDrive(NBTTagCompound data) - { - data.setInteger( "priority", this.priority ); - } - @MENetworkEventSubscribe - public void powerRender(MENetworkPowerStatusChange c) + public void channelRender( MENetworkChannelsChanged c ) { this.recalculateDisplay(); } - @MENetworkEventSubscribe - public void channelRender(MENetworkChannelsChanged c) - { - this.recalculateDisplay(); - } - - public TileDrive() { - this.mySrc = new MachineSource( this ); - this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); - } - @Override - public AECableType getCableConnectionType(ForgeDirection dir) + public AECableType getCableConnectionType( ForgeDirection dir ) { return AECableType.SMART; } @@ -182,16 +236,15 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior } @Override - public void onReady() + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { - super.onReady(); - this.updateState(); + return itemstack != null && AEApi.instance().registries().cell().isCellHandled( itemstack ); } @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) { - if ( this.isCached ) + if( this.isCached ) { this.isCached = false; // recalculate the storage cell. this.updateState(); @@ -204,7 +257,7 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior IStorageGrid gs = this.gridProxy.getStorage(); Platform.postChanges( gs, removed, added, this.mySrc ); } - catch (GridAccessException ignored) + catch( GridAccessException ignored ) { } @@ -212,35 +265,35 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior } @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) + public int[] getAccessibleSlotsBySide( ForgeDirection side ) { return this.sides; } public void updateState() { - if ( !this.isCached ) + if( !this.isCached ) { this.items = new LinkedList(); this.fluids = new LinkedList(); double power = 2.0; - for (int x = 0; x < this.inv.getSizeInventory(); x++) + for( int x = 0; x < this.inv.getSizeInventory(); x++ ) { ItemStack is = this.inv.getStackInSlot( x ); this.invBySlot[x] = null; this.handlersBySlot[x] = null; - if ( is != null ) + if( is != null ) { this.handlersBySlot[x] = AEApi.instance().registries().cell().getHandler( is ); - if ( this.handlersBySlot[x] != null ) + if( this.handlersBySlot[x] != null ) { IMEInventoryHandler cell = this.handlersBySlot[x].getCellInventory( is, this, StorageChannel.ITEMS ); - if ( cell != null ) + if( cell != null ) { power += this.handlersBySlot[x].cellIdleDrain( is, cell ); @@ -253,7 +306,7 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior { cell = this.handlersBySlot[x].getCellInventory( is, this, StorageChannel.FLUIDS ); - if ( cell != null ) + if( cell != null ) { power += this.handlersBySlot[x].cellIdleDrain( is, cell ); @@ -274,12 +327,19 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior } @Override - public List getCellArray(StorageChannel channel) + public void onReady() { - if ( this.gridProxy.isActive() ) + super.onReady(); + this.updateState(); + } + + @Override + public List getCellArray( StorageChannel channel ) + { + if( this.gridProxy.isActive() ) { this.updateState(); - return (List) (channel == StorageChannel.ITEMS ? this.items : this.fluids); + return (List) ( channel == StorageChannel.ITEMS ? this.items : this.fluids ); } return new ArrayList(); } @@ -291,73 +351,7 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior } @Override - public int getCellCount() - { - return 10; - } - - @Override - public void blinkCell(int slot) - { - long now = this.worldObj.getTotalWorldTime(); - if ( now - this.lastStateChange > 8 ) - this.state = 0; - this.lastStateChange = now; - - this.state |= 1 << (slot * 3 + 2); - - this.recalculateDisplay(); - } - - @Override - public boolean isCellBlinking(int slot) - { - long now = this.worldObj.getTotalWorldTime(); - if ( now - this.lastStateChange > 8 ) - return false; - - return ((this.state >> (slot * 3 + 2)) & 0x01) == 0x01; - } - - @Override - public int getCellStatus(int slot) - { - if ( Platform.isClient() ) - return (this.state >> (slot * 3)) & 3; - - ItemStack cell = this.inv.getStackInSlot( 2 ); - ICellHandler ch = this.handlersBySlot[slot]; - - MEInventoryHandler handler = this.invBySlot[slot]; - if ( handler == null ) - return 0; - - if ( handler.getChannel() == StorageChannel.ITEMS ) - { - if ( ch != null ) - return ch.getStatusForCell( cell, handler.getInternal() ); - } - - if ( handler.getChannel() == StorageChannel.FLUIDS ) - { - if ( ch != null ) - return ch.getStatusForCell( cell, handler.getInternal() ); - } - - return 0; - } - - @Override - public boolean isPowered() - { - if ( Platform.isClient() ) - return (this.state & 0x80000000) == 0x80000000; - - return this.gridProxy.isActive(); - } - - @Override - public void setPriority(int newValue) + public void setPriority( int newValue ) { this.priority = newValue; this.markDirty(); @@ -369,20 +363,27 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior { this.gridProxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); } - catch (GridAccessException e) + catch( GridAccessException e ) { // :P } } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public void blinkCell( int slot ) { - return itemstack != null && AEApi.instance().registries().cell().isCellHandled( itemstack ); + long now = this.worldObj.getTotalWorldTime(); + if( now - this.lastStateChange > 8 ) + this.state = 0; + this.lastStateChange = now; + + this.state |= 1 << ( slot * 3 + 2 ); + + this.recalculateDisplay(); } @Override - public void saveChanges(IMEInventory cellInventory) + public void saveChanges( IMEInventory cellInventory ) { this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); } diff --git a/src/main/java/appeng/tile/storage/TileIOPort.java b/src/main/java/appeng/tile/storage/TileIOPort.java index 630096a94..7777fe062 100644 --- a/src/main/java/appeng/tile/storage/TileIOPort.java +++ b/src/main/java/appeng/tile/storage/TileIOPort.java @@ -230,6 +230,21 @@ public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IC return false; } + @Override + public IInventory getInternalInventory() + { + return this.cells; + } + + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) + { + if( this.cells == inv ) + { + this.updateTask(); + } + } + @Override public boolean canInsertItem( int slotIndex, ItemStack insertingItem, int side ) { @@ -258,21 +273,6 @@ public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IC return false; } - @Override - public IInventory getInternalInventory() - { - return this.cells; - } - - @Override - public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) - { - if( this.cells == inv ) - { - this.updateTask(); - } - } - @Override public int[] getAccessibleSlotsBySide( ForgeDirection d ) { diff --git a/src/main/java/appeng/tile/storage/TileSkyChest.java b/src/main/java/appeng/tile/storage/TileSkyChest.java index f30718d4d..ca8f902aa 100644 --- a/src/main/java/appeng/tile/storage/TileSkyChest.java +++ b/src/main/java/appeng/tile/storage/TileSkyChest.java @@ -18,6 +18,7 @@ package appeng.tile.storage; + import io.netty.buffer.ByteBuf; import net.minecraft.inventory.IInventory; @@ -31,70 +32,57 @@ import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.InvOperation; import appeng.util.Platform; + public class TileSkyChest extends AEBaseInvTile { final int[] sides = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35 }; final AppEngInternalInventory inv = new AppEngInternalInventory( this, 9 * 4 ); + // server + public int playerOpen; + // client.. + public long lastEvent; + public float lidAngle; - @TileEvent(TileEventType.NETWORK_WRITE) - public void writeToStream_TileSkyChest(ByteBuf data) + @TileEvent( TileEventType.NETWORK_WRITE ) + public void writeToStream_TileSkyChest( ByteBuf data ) { data.writeBoolean( this.playerOpen > 0 ); } - @TileEvent(TileEventType.NETWORK_READ) - public boolean readFromStream_TileSkyChest(ByteBuf data) + @TileEvent( TileEventType.NETWORK_READ ) + public boolean readFromStream_TileSkyChest( ByteBuf data ) { int wasOpen = this.playerOpen; this.playerOpen = data.readBoolean() ? 1 : 0; - if ( wasOpen != this.playerOpen ) + if( wasOpen != this.playerOpen ) this.lastEvent = System.currentTimeMillis(); return false; // TESR yo! } - // server - public int playerOpen; - - // client.. - public long lastEvent; - public float lidAngle; - @Override public boolean requiresTESR() { return true; } - @Override - public void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added) - { - - } - @Override public IInventory getInternalInventory() { return this.inv; } - @Override - public int[] getAccessibleSlotsBySide(ForgeDirection side) - { - return this.sides; - } - @Override public void openInventory() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; this.playerOpen++; - if ( this.playerOpen == 1 ) + if( this.playerOpen == 1 ) { this.getWorldObj().playSoundEffect( this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D, "random.chestopen", 0.5F, this.getWorldObj().rand.nextFloat() * 0.1F + 0.9F ); this.markForUpdate(); @@ -104,20 +92,30 @@ public class TileSkyChest extends AEBaseInvTile @Override public void closeInventory() { - if ( Platform.isClient() ) + if( Platform.isClient() ) return; this.playerOpen--; - if ( this.playerOpen < 0 ) + if( this.playerOpen < 0 ) this.playerOpen = 0; - if ( this.playerOpen == 0 ) + if( this.playerOpen == 0 ) { - this.getWorldObj().playSoundEffect( this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D, "random.chestclosed", 0.5F, - this.getWorldObj().rand.nextFloat() * 0.1F + 0.9F ); + this.getWorldObj().playSoundEffect( this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D, "random.chestclosed", 0.5F, this.getWorldObj().rand.nextFloat() * 0.1F + 0.9F ); this.markForUpdate(); } } + @Override + public void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ) + { + + } + + @Override + public int[] getAccessibleSlotsBySide( ForgeDirection side ) + { + return this.sides; + } } diff --git a/src/main/java/appeng/transformer/AppEngCore.java b/src/main/java/appeng/transformer/AppEngCore.java index a4406dfce..4e659d0d6 100644 --- a/src/main/java/appeng/transformer/AppEngCore.java +++ b/src/main/java/appeng/transformer/AppEngCore.java @@ -18,9 +18,8 @@ package appeng.transformer; -import java.util.Map; -import com.google.common.eventbus.EventBus; +import java.util.Map; import cpw.mods.fml.common.DummyModContainer; import cpw.mods.fml.common.LoadController; @@ -31,9 +30,12 @@ import cpw.mods.fml.relauncher.FMLRelaunchLog; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; +import com.google.common.eventbus.EventBus; + import appeng.core.AEConfig; -@MCVersion("1.7.10") + +@MCVersion( "1.7.10" ) public class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin { @@ -41,7 +43,8 @@ public class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin protected final ModMetadata md = new ModMetadata(); - public AppEngCore() { + public AppEngCore() + { this.instance = this; FMLRelaunchLog.info( "[AppEng] Core Init" ); this.md.autogenerated = false; @@ -55,16 +58,10 @@ public class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin } @EventHandler - public void load(FMLInitializationEvent event) + public void load( FMLInitializationEvent event ) { } - @Override - public boolean registerBus(EventBus bus, LoadController controller) - { - return true; - } - @Override public String[] getASMTransformerClass() { @@ -84,11 +81,23 @@ public class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin } @Override - public void injectData(Map data) + public void injectData( Map data ) { } + @Override + public String getAccessTransformerClass() + { + return "appeng.transformer.asm.ASMTweaker"; + } + + @Override + public ModMetadata getMetadata() + { + return this.md; + } + @Override public String getModId() { @@ -107,21 +116,15 @@ public class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin return AEConfig.VERSION; } + @Override + public boolean registerBus( EventBus bus, LoadController controller ) + { + return true; + } + @Override public String getDisplayVersion() { return this.getVersion(); } - - @Override - public ModMetadata getMetadata() - { - return this.md; - } - - @Override - public String getAccessTransformerClass() - { - return "appeng.transformer.asm.ASMTweaker"; - } } diff --git a/src/main/java/appeng/transformer/MissingCoreMod.java b/src/main/java/appeng/transformer/MissingCoreMod.java index a494831f7..4f112cc57 100644 --- a/src/main/java/appeng/transformer/MissingCoreMod.java +++ b/src/main/java/appeng/transformer/MissingCoreMod.java @@ -18,11 +18,13 @@ package appeng.transformer; + import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiErrorScreen; import cpw.mods.fml.client.CustomModLoadingErrorDisplayException; + public class MissingCoreMod extends CustomModLoadingErrorDisplayException { @@ -30,7 +32,7 @@ public class MissingCoreMod extends CustomModLoadingErrorDisplayException private boolean deobf = false; @Override - public void initGui(GuiErrorScreen errorScreen, FontRenderer fontRenderer) + public void initGui( GuiErrorScreen errorScreen, FontRenderer fontRenderer ) { Class clz = errorScreen.getClass(); try @@ -38,14 +40,14 @@ public class MissingCoreMod extends CustomModLoadingErrorDisplayException clz.getField( "mc" ); this.deobf = true; } - catch (Throwable ignored) + catch( Throwable ignored ) { } } @Override - public void drawScreen(GuiErrorScreen errorScreen, FontRenderer fontRenderer, int mouseRelX, int mouseRelY, float tickTime) + public void drawScreen( GuiErrorScreen errorScreen, FontRenderer fontRenderer, int mouseRelX, int mouseRelY, float tickTime ) { int offset = 10; this.drawCenteredString( fontRenderer, "Sorry, couldn't load AE2 Properly.", errorScreen.width / 2, offset += 15, 0xffffff ); @@ -53,7 +55,7 @@ public class MissingCoreMod extends CustomModLoadingErrorDisplayException offset += 15; - if ( this.deobf ) + if( this.deobf ) { offset += 15; this.drawCenteredString( fontRenderer, "In a developer environment add the following too your args,", errorScreen.width / 2, offset += 15, 0xffffff ); @@ -75,7 +77,7 @@ public class MissingCoreMod extends CustomModLoadingErrorDisplayException } } - public void drawCenteredString(FontRenderer fontRenderer, String string, int x, int y, int colour) + public void drawCenteredString( FontRenderer fontRenderer, String string, int x, int y, int colour ) { fontRenderer.drawStringWithShadow( string, x - fontRenderer.getStringWidth( string.replaceAll( "\\P{InBasic_Latin}", "" ) ) / 2, y, colour ); } diff --git a/src/main/java/appeng/transformer/asm/ASMIntegration.java b/src/main/java/appeng/transformer/asm/ASMIntegration.java index d8fcee65f..7326fe4b3 100644 --- a/src/main/java/appeng/transformer/asm/ASMIntegration.java +++ b/src/main/java/appeng/transformer/asm/ASMIntegration.java @@ -48,7 +48,7 @@ public class ASMIntegration implements IClassTransformer * Side, Display Name, ModID ClassPostFix */ - for ( IntegrationType type : IntegrationType.values() ) + for( IntegrationType type : IntegrationType.values() ) { IntegrationRegistry.INSTANCE.add( type ); } @@ -67,10 +67,10 @@ public class ASMIntegration implements IClassTransformer @Override public byte[] transform( String name, String transformedName, byte[] basicClass ) { - if ( basicClass == null || transformedName.startsWith( "appeng.transformer" ) ) + if( basicClass == null || transformedName.startsWith( "appeng.transformer" ) ) return basicClass; - if ( transformedName.startsWith( "appeng." ) ) + if( transformedName.startsWith( "appeng." ) ) { // log( "Found " + transformedName ); @@ -82,14 +82,14 @@ public class ASMIntegration implements IClassTransformer { boolean reWrite = this.removeOptionals( classNode ); - if ( reWrite ) + if( reWrite ) { ClassWriter writer = new ClassWriter( ClassWriter.COMPUTE_MAXS ); classNode.accept( writer ); return writer.toByteArray(); } } - catch ( Throwable t ) + catch( Throwable t ) { t.printStackTrace(); } @@ -101,20 +101,20 @@ public class ASMIntegration implements IClassTransformer { boolean changed = false; - if ( classNode.visibleAnnotations != null ) + if( classNode.visibleAnnotations != null ) { - for ( AnnotationNode an : classNode.visibleAnnotations ) + for( AnnotationNode an : classNode.visibleAnnotations ) { - if ( this.hasAnnotation( an, Integration.Interface.class ) ) + if( this.hasAnnotation( an, Integration.Interface.class ) ) { - if ( this.stripInterface( classNode, Integration.Interface.class, an ) ) + if( this.stripInterface( classNode, Integration.Interface.class, an ) ) changed = true; } - else if ( this.hasAnnotation( an, Integration.InterfaceList.class ) ) + else if( this.hasAnnotation( an, Integration.InterfaceList.class ) ) { - for ( Object o : ( ( List ) an.values.get( 1 ) ) ) + for( Object o : ( (List) an.values.get( 1 ) ) ) { - if ( this.stripInterface( classNode, Integration.InterfaceList.class, ( AnnotationNode ) o ) ) + if( this.stripInterface( classNode, Integration.InterfaceList.class, (AnnotationNode) o ) ) changed = true; } } @@ -122,25 +122,24 @@ public class ASMIntegration implements IClassTransformer } Iterator i = classNode.methods.iterator(); - while ( i.hasNext() ) + while( i.hasNext() ) { MethodNode mn = i.next(); - if ( mn.visibleAnnotations != null ) + if( mn.visibleAnnotations != null ) { - for ( AnnotationNode an : mn.visibleAnnotations ) + for( AnnotationNode an : mn.visibleAnnotations ) { - if ( this.hasAnnotation( an, Integration.Method.class ) ) + if( this.hasAnnotation( an, Integration.Method.class ) ) { - if ( this.stripMethod( classNode, mn, i, Integration.Method.class, an ) ) + if( this.stripMethod( classNode, mn, i, Integration.Method.class, an ) ) changed = true; } } - } } - if ( changed ) + if( changed ) this.log( "Updated " + classNode.name ); return changed; @@ -151,57 +150,29 @@ public class ASMIntegration implements IClassTransformer return ann.desc.equals( Type.getDescriptor( annotation ) ); } - private boolean stripMethod( ClassNode classNode, MethodNode mn, Iterator i, Class class1, AnnotationNode an ) - { - if ( an.values.size() != 2 ) - throw new RuntimeException( "Unable to handle Method annotation on " + classNode.name ); - - String iName = null; - - if ( an.values.get( 0 ).equals( "iname" ) ) - iName = ( String ) an.values.get( 1 ); - - if ( iName != null ) - { - IntegrationType type = IntegrationType.valueOf( iName ); - if ( !IntegrationRegistry.INSTANCE.isEnabled( type ) ) - { - this.log( "Removing Method " + mn.name + " from " + classNode.name + " because " + iName + " integration is disabled." ); - i.remove(); - return true; - } - else - this.log( "Allowing Method " + mn.name + " from " + classNode.name + " because " + iName + " integration is enabled." ); - } - else - throw new RuntimeException( "Unable to handle Method annotation on " + classNode.name ); - - return false; - } - private boolean stripInterface( ClassNode classNode, Class class1, AnnotationNode an ) { - if ( an.values.size() != 4 ) + if( an.values.size() != 4 ) throw new RuntimeException( "Unable to handle Interface annotation on " + classNode.name ); String iFace = null; String iName = null; - if ( an.values.get( 0 ).equals( "iface" ) ) - iFace = ( String ) an.values.get( 1 ); - else if ( an.values.get( 2 ).equals( "iface" ) ) - iFace = ( String ) an.values.get( 3 ); + if( an.values.get( 0 ).equals( "iface" ) ) + iFace = (String) an.values.get( 1 ); + else if( an.values.get( 2 ).equals( "iface" ) ) + iFace = (String) an.values.get( 3 ); - if ( an.values.get( 0 ).equals( "iname" ) ) - iName = ( String ) an.values.get( 1 ); - else if ( an.values.get( 2 ).equals( "iname" ) ) - iName = ( String ) an.values.get( 3 ); + if( an.values.get( 0 ).equals( "iname" ) ) + iName = (String) an.values.get( 1 ); + else if( an.values.get( 2 ).equals( "iname" ) ) + iName = (String) an.values.get( 3 ); IntegrationType type = IntegrationType.valueOf( iName ); - if ( iName != null && iFace != null ) + if( iName != null && iFace != null ) { - if ( !IntegrationRegistry.INSTANCE.isEnabled( type ) ) + if( !IntegrationRegistry.INSTANCE.isEnabled( type ) ) { this.log( "Removing Interface " + iFace + " from " + classNode.name + " because " + iName + " integration is disabled." ); classNode.interfaces.remove( iFace.replace( '.', '/' ) ); @@ -216,9 +187,36 @@ public class ASMIntegration implements IClassTransformer return false; } + private boolean stripMethod( ClassNode classNode, MethodNode mn, Iterator i, Class class1, AnnotationNode an ) + { + if( an.values.size() != 2 ) + throw new RuntimeException( "Unable to handle Method annotation on " + classNode.name ); + + String iName = null; + + if( an.values.get( 0 ).equals( "iname" ) ) + iName = (String) an.values.get( 1 ); + + if( iName != null ) + { + IntegrationType type = IntegrationType.valueOf( iName ); + if( !IntegrationRegistry.INSTANCE.isEnabled( type ) ) + { + this.log( "Removing Method " + mn.name + " from " + classNode.name + " because " + iName + " integration is disabled." ); + i.remove(); + return true; + } + else + this.log( "Allowing Method " + mn.name + " from " + classNode.name + " because " + iName + " integration is enabled." ); + } + else + throw new RuntimeException( "Unable to handle Method annotation on " + classNode.name ); + + return false; + } + private void log( String string ) { FMLRelaunchLog.log( "AE2-CORE", Level.INFO, string ); } - } diff --git a/src/main/java/appeng/transformer/asm/ASMTweaker.java b/src/main/java/appeng/transformer/asm/ASMTweaker.java index 20045f158..1b19d6a54 100644 --- a/src/main/java/appeng/transformer/asm/ASMTweaker.java +++ b/src/main/java/appeng/transformer/asm/ASMTweaker.java @@ -18,6 +18,7 @@ package appeng.transformer.asm; + import java.util.Iterator; import org.apache.logging.log4j.Level; @@ -38,25 +39,14 @@ import cpw.mods.fml.relauncher.FMLRelaunchLog; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; + public class ASMTweaker implements IClassTransformer { - class publicLine - { - - public publicLine(String name, String desc) { - this.name = name; - this.desc = desc; - } - - final String name; - final String desc; - - } - final Multimap privateToPublicMethods = HashMultimap.create(); - public ASMTweaker() { + public ASMTweaker() + { this.privateToPublicMethods.put( "net.minecraft.client.gui.inventory.GuiContainer", new publicLine( "func_146977_a", "(Lnet/minecraft/inventory/Slot;)V" ) ); this.privateToPublicMethods.put( "net.minecraft.client.gui.inventory.GuiContainer", new publicLine( "a", "(Lzk;)V" ) ); @@ -70,30 +60,30 @@ public class ASMTweaker implements IClassTransformer } @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) + public byte[] transform( String name, String transformedName, byte[] basicClass ) { - if ( basicClass == null ) + if( basicClass == null ) return null; try { - if ( transformedName != null && this.privateToPublicMethods.containsKey( transformedName ) ) + if( transformedName != null && this.privateToPublicMethods.containsKey( transformedName ) ) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader( basicClass ); classReader.accept( classNode, 0 ); - for (publicLine Set : this.privateToPublicMethods.get( transformedName )) + for( publicLine Set : this.privateToPublicMethods.get( transformedName ) ) { this.makePublic( classNode, Set ); } // CALL VIRTUAL! - if ( transformedName.equals( "net.minecraft.client.gui.inventory.GuiContainer" ) ) + if( transformedName.equals( "net.minecraft.client.gui.inventory.GuiContainer" ) ) { - for (MethodNode mn : classNode.methods) + for( MethodNode mn : classNode.methods ) { - if ( mn.name.equals( "func_146977_a" ) || (mn.name.equals( "a" ) && mn.desc.equals( "(Lzk;)V" )) ) + if( mn.name.equals( "func_146977_a" ) || ( mn.name.equals( "a" ) && mn.desc.equals( "(Lzk;)V" ) ) ) { MethodNode newNode = new MethodNode( Opcodes.ACC_PUBLIC, "func_146977_a_original", mn.desc, mn.signature, new String[0] ); newNode.instructions.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); @@ -106,18 +96,18 @@ public class ASMTweaker implements IClassTransformer } } - for (MethodNode mn : classNode.methods) + for( MethodNode mn : classNode.methods ) { - if ( mn.name.equals( "func_73863_a" ) || mn.name.equals( "drawScreen" ) || (mn.name.equals( "a" ) && mn.desc.equals( "(IIF)V" )) ) + if( mn.name.equals( "func_73863_a" ) || mn.name.equals( "drawScreen" ) || ( mn.name.equals( "a" ) && mn.desc.equals( "(IIF)V" ) ) ) { Iterator i = mn.instructions.iterator(); - while (i.hasNext()) + while( i.hasNext() ) { AbstractInsnNode in = i.next(); - if ( in.getOpcode() == Opcodes.INVOKESPECIAL ) + if( in.getOpcode() == Opcodes.INVOKESPECIAL ) { MethodInsnNode n = (MethodInsnNode) in; - if ( n.name.equals( "func_146977_a" ) || (n.name.equals( "a" ) && n.desc.equals( "(Lzk;)V" )) ) + if( n.name.equals( "func_146977_a" ) || ( n.name.equals( "a" ) && n.desc.equals( "(Lzk;)V" ) ) ) { this.log( n.name + n.desc + " - Invoke Virtual" ); mn.instructions.insertBefore( n, new MethodInsnNode( Opcodes.INVOKEVIRTUAL, n.owner, n.name, n.desc, false ) ); @@ -135,27 +125,40 @@ public class ASMTweaker implements IClassTransformer return writer.toByteArray(); } } - catch (Throwable ignored) + catch( Throwable ignored ) { } return basicClass; } - private void log(String string) + private void makePublic( ClassNode classNode, publicLine set ) { - FMLRelaunchLog.log( "AE2-CORE", Level.INFO, string ); - } - - private void makePublic(ClassNode classNode, publicLine set) - { - for (MethodNode mn : classNode.methods) + for( MethodNode mn : classNode.methods ) { - if ( mn.name.equals( set.name ) && mn.desc.equals( set.desc ) ) + if( mn.name.equals( set.name ) && mn.desc.equals( set.desc ) ) { - mn.access = (mn.access & (~(Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED))) | Opcodes.ACC_PUBLIC; + mn.access = ( mn.access & ( ~( Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED ) ) ) | Opcodes.ACC_PUBLIC; this.log( mn.name + mn.desc + " - Transformed" ); } } } + + private void log( String string ) + { + FMLRelaunchLog.log( "AE2-CORE", Level.INFO, string ); + } + + class publicLine + { + + final String name; + final String desc; + + public publicLine( String name, String desc ) + { + this.name = name; + this.desc = desc; + } + } } diff --git a/src/main/java/appeng/util/BlockUpdate.java b/src/main/java/appeng/util/BlockUpdate.java index a87a066af..9d2089279 100644 --- a/src/main/java/appeng/util/BlockUpdate.java +++ b/src/main/java/appeng/util/BlockUpdate.java @@ -18,10 +18,12 @@ package appeng.util; + import java.util.concurrent.Callable; import net.minecraft.world.World; + public class BlockUpdate implements Callable { @@ -30,7 +32,8 @@ public class BlockUpdate implements Callable final int y; final int z; - public BlockUpdate(World w, int x, int y, int z) { + public BlockUpdate( World w, int x, int y, int z ) + { this.w = w; this.x = x; this.y = y; @@ -40,10 +43,9 @@ public class BlockUpdate implements Callable @Override public Object call() throws Exception { - if ( this.w.blockExists( this.x, this.y, this.z ) ) + if( this.w.blockExists( this.x, this.y, this.z ) ) this.w.notifyBlocksOfNeighborChange( this.x, this.y, this.z, Platform.AIR ); return true; } - } diff --git a/src/main/java/appeng/util/ClassInstantiation.java b/src/main/java/appeng/util/ClassInstantiation.java index 63b67aaa7..7c9f4681f 100644 --- a/src/main/java/appeng/util/ClassInstantiation.java +++ b/src/main/java/appeng/util/ClassInstantiation.java @@ -41,37 +41,37 @@ public class ClassInstantiation public Optional get() { @SuppressWarnings( "unchecked" ) - Constructor[] constructors = ( Constructor[] ) this.template.getConstructors(); + Constructor[] constructors = (Constructor[]) this.template.getConstructors(); - for ( Constructor constructor : constructors ) + for( Constructor constructor : constructors ) { Class[] paramTypes = constructor.getParameterTypes(); - if ( paramTypes.length == this.args.length ) + if( paramTypes.length == this.args.length ) { boolean valid = true; - for ( int idx = 0; idx < paramTypes.length; idx++ ) + for( int idx = 0; idx < paramTypes.length; idx++ ) { Class cz = this.args[idx].getClass(); - if ( !this.isClassMatch( paramTypes[idx], cz, this.args[idx] ) ) + if( !this.isClassMatch( paramTypes[idx], cz, this.args[idx] ) ) valid = false; } - if ( valid ) + if( valid ) { try { return Optional.of( constructor.newInstance( this.args ) ); } - catch ( InstantiationException e ) + catch( InstantiationException e ) { e.printStackTrace(); } - catch ( IllegalAccessException e ) + catch( IllegalAccessException e ) { e.printStackTrace(); } - catch ( InvocationTargetException e ) + catch( InvocationTargetException e ) { e.printStackTrace(); } @@ -85,7 +85,7 @@ public class ClassInstantiation private boolean isClassMatch( Class expected, Class got, Object value ) { - if ( value == null && !expected.isPrimitive() ) + if( value == null && !expected.isPrimitive() ) return true; expected = this.condense( expected, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class ); @@ -96,16 +96,16 @@ public class ClassInstantiation private Class condense( Class expected, Class... wrappers ) { - if ( expected.isPrimitive() ) + if( expected.isPrimitive() ) { - for ( Class clz : wrappers ) + for( Class clz : wrappers ) { try { - if ( expected == clz.getField( "TYPE" ).get( null ) ) + if( expected == clz.getField( "TYPE" ).get( null ) ) return clz; } - catch ( Throwable t ) + catch( Throwable t ) { AELog.error( t ); } diff --git a/src/main/java/appeng/util/ConfigManager.java b/src/main/java/appeng/util/ConfigManager.java index b807d6595..450e79ed1 100644 --- a/src/main/java/appeng/util/ConfigManager.java +++ b/src/main/java/appeng/util/ConfigManager.java @@ -59,7 +59,7 @@ public final class ConfigManager implements IConfigManager { Enum oldValue = this.settings.get( settingName ); - if ( oldValue != null ) + if( oldValue != null ) return oldValue; throw new RuntimeException( "Invalid Config setting" ); @@ -83,7 +83,7 @@ public final class ConfigManager implements IConfigManager public void writeToNBT( NBTTagCompound tagCompound ) { - for ( Settings setting : this.settings.keySet() ) + for( Settings setting : this.settings.keySet() ) { tagCompound.setString( setting.name(), this.settings.get( setting ).toString() ); } @@ -97,20 +97,20 @@ public final class ConfigManager implements IConfigManager @Override public void readFromNBT( NBTTagCompound tagCompound ) { - for ( Settings key : this.settings.keySet() ) + for( Settings key : this.settings.keySet() ) { try { - if ( tagCompound.hasKey( key.name() ) ) + if( tagCompound.hasKey( key.name() ) ) { String value = tagCompound.getString( key.name() ); // Provides an upgrade path for the rename of this value in the API between rv1 and rv2 - if ( value.equals( "EXTACTABLE_ONLY" ) ) + if( value.equals( "EXTACTABLE_ONLY" ) ) { value = StorageFilter.EXTRACTABLE_ONLY.toString(); } - else if ( value.equals( "STOREABLE_AMOUNT" ) ) + else if( value.equals( "STOREABLE_AMOUNT" ) ) { value = LevelEmitterMode.STORABLE_AMOUNT.toString(); } @@ -122,7 +122,7 @@ public final class ConfigManager implements IConfigManager this.putSetting( key, newValue ); } } - catch ( IllegalArgumentException e ) + catch( IllegalArgumentException e ) { AELog.error( e ); } diff --git a/src/main/java/appeng/util/IConfigManagerHost.java b/src/main/java/appeng/util/IConfigManagerHost.java index d7ba27343..1323a7df5 100644 --- a/src/main/java/appeng/util/IConfigManagerHost.java +++ b/src/main/java/appeng/util/IConfigManagerHost.java @@ -18,11 +18,12 @@ package appeng.util; + import appeng.api.util.IConfigManager; + public interface IConfigManagerHost { - void updateSetting(IConfigManager manager, Enum settingName, Enum newValue); - + void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ); } diff --git a/src/main/java/appeng/util/InWorldToolOperationResult.java b/src/main/java/appeng/util/InWorldToolOperationResult.java index dbb1ce613..303c11b3b 100644 --- a/src/main/java/appeng/util/InWorldToolOperationResult.java +++ b/src/main/java/appeng/util/InWorldToolOperationResult.java @@ -18,6 +18,7 @@ package appeng.util; + import java.util.ArrayList; import java.util.List; @@ -25,24 +26,43 @@ import net.minecraft.block.Block; import net.minecraft.block.BlockAir; import net.minecraft.item.ItemStack; + public class InWorldToolOperationResult { public final ItemStack BlockItem; public final List Drops; - public static InWorldToolOperationResult getBlockOperationResult(ItemStack[] items) + public InWorldToolOperationResult() + { + this.BlockItem = null; + this.Drops = null; + } + + public InWorldToolOperationResult( ItemStack block, List drops ) + { + this.BlockItem = block; + this.Drops = drops; + } + + public InWorldToolOperationResult( ItemStack block ) + { + this.BlockItem = block; + this.Drops = null; + } + + public static InWorldToolOperationResult getBlockOperationResult( ItemStack[] items ) { List temp = new ArrayList(); ItemStack b = null; - for (ItemStack l : items) + for( ItemStack l : items ) { - if ( b == null ) + if( b == null ) { Block bl = Block.getBlockFromItem( l.getItem() ); - if ( bl != null && !(bl instanceof BlockAir) ) + if( bl != null && !( bl instanceof BlockAir ) ) { b = l; continue; @@ -54,19 +74,4 @@ public class InWorldToolOperationResult return new InWorldToolOperationResult( b, temp ); } - - public InWorldToolOperationResult() { - this.BlockItem = null; - this.Drops = null; - } - - public InWorldToolOperationResult(ItemStack block, List drops) { - this.BlockItem = block; - this.Drops = drops; - } - - public InWorldToolOperationResult(ItemStack block) { - this.BlockItem = block; - this.Drops = null; - } } diff --git a/src/main/java/appeng/util/InventoryAdaptor.java b/src/main/java/appeng/util/InventoryAdaptor.java index ecb775c7d..22e96ac73 100644 --- a/src/main/java/appeng/util/InventoryAdaptor.java +++ b/src/main/java/appeng/util/InventoryAdaptor.java @@ -18,6 +18,7 @@ package appeng.util; + import java.util.ArrayList; import net.minecraft.entity.player.EntityPlayer; @@ -38,67 +39,68 @@ import appeng.util.inv.IInventoryDestination; import appeng.util.inv.ItemSlot; import appeng.util.inv.WrapperMCISidedInventory; + public abstract class InventoryAdaptor implements Iterable { - // return what was extracted. - public abstract ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination); - - public abstract ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination); - - // return what was extracted. - public abstract ItemStack removeSimilarItems(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination); - - public abstract ItemStack simulateSimilarRemove(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination); - - // return what isn't used... - public abstract ItemStack addItems(ItemStack toBeAdded); - - public abstract ItemStack simulateAdd(ItemStack toBeSimulated); - - public abstract boolean containsItems(); - // returns an appropriate adaptor, or null - public static InventoryAdaptor getAdaptor(Object te, ForgeDirection d) + public static InventoryAdaptor getAdaptor( Object te, ForgeDirection d ) { - if ( te == null ) + if( te == null ) return null; - IBetterStorage bs = (IBetterStorage) (AppEng.instance.isIntegrationEnabled( IntegrationType.BetterStorage ) ? AppEng.instance.getIntegration( IntegrationType.BetterStorage ) : null); + IBetterStorage bs = (IBetterStorage) ( AppEng.instance.isIntegrationEnabled( IntegrationType.BetterStorage ) ? AppEng.instance.getIntegration( IntegrationType.BetterStorage ) : null ); - if ( te instanceof EntityPlayer ) + if( te instanceof EntityPlayer ) { - return new AdaptorIInventory( new AdaptorPlayerInventory( ((EntityPlayer) te).inventory, false ) ); + return new AdaptorIInventory( new AdaptorPlayerInventory( ( (EntityPlayer) te ).inventory, false ) ); } - else if ( te instanceof ArrayList ) + else if( te instanceof ArrayList ) { @SuppressWarnings( "unchecked" ) - final ArrayList list = ( ArrayList ) te; + final ArrayList list = (ArrayList) te; return new AdaptorList( list ); } - else if ( bs != null && bs.isStorageCrate( te ) ) + else if( bs != null && bs.isStorageCrate( te ) ) { return bs.getAdaptor( te, d ); } - else if ( te instanceof TileEntityChest ) + else if( te instanceof TileEntityChest ) { return new AdaptorIInventory( Platform.GetChestInv( te ) ); } - else if ( te instanceof ISidedInventory ) + else if( te instanceof ISidedInventory ) { - ISidedInventory si =(ISidedInventory)te; + ISidedInventory si = (ISidedInventory) te; int[] slots = si.getAccessibleSlotsFromSide( d.ordinal() ); - if ( si.getSizeInventory() > 0 && slots != null && slots.length > 0 ) + if( si.getSizeInventory() > 0 && slots != null && slots.length > 0 ) return new AdaptorIInventory( new WrapperMCISidedInventory( si, d ) ); } - else if ( te instanceof IInventory ) + else if( te instanceof IInventory ) { - IInventory i =(IInventory)te; - if ( i.getSizeInventory() > 0 ) + IInventory i = (IInventory) te; + if( i.getSizeInventory() > 0 ) return new AdaptorIInventory( i ); } return null; } + + // return what was extracted. + public abstract ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ); + + public abstract ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ); + + // return what was extracted. + public abstract ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ); + + public abstract ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ); + + // return what isn't used... + public abstract ItemStack addItems( ItemStack toBeAdded ); + + public abstract ItemStack simulateAdd( ItemStack toBeSimulated ); + + public abstract boolean containsItems(); } diff --git a/src/main/java/appeng/util/ItemSorters.java b/src/main/java/appeng/util/ItemSorters.java index 44d3268ec..4df2faf67 100644 --- a/src/main/java/appeng/util/ItemSorters.java +++ b/src/main/java/appeng/util/ItemSorters.java @@ -18,6 +18,7 @@ package appeng.util; + import java.util.Comparator; import appeng.api.config.SortDir; @@ -27,108 +28,108 @@ import appeng.integration.IntegrationType; import appeng.integration.abstraction.IInvTweaks; import appeng.util.item.AEItemStack; + public class ItemSorters { public static SortDir Direction = SortDir.ASCENDING; - private static IInvTweaks api; - - public static void init() + public static final Comparator CONFIG_BASED_SORT_BY_NAME = new Comparator() { - if ( api != null ) - return; - - if ( AppEng.instance.isIntegrationEnabled( IntegrationType.InvTweaks ) ) - api = (IInvTweaks) AppEng.instance.getIntegration( IntegrationType.InvTweaks ); - else - api = null; - } - - public static int compareInt(int a, int b) - { - if ( a == b ) - return 0; - if ( a < b ) - return -1; - return 1; - } - - public static int compareLong(long a, long b) - { - if ( a == b ) - return 0; - if ( a < b ) - return -1; - return 1; - } - - public static int compareDouble(double a, double b) - { - if ( a == b ) - return 0; - if ( a < b ) - return -1; - return 1; - } - - public static final Comparator CONFIG_BASED_SORT_BY_NAME = new Comparator() { @Override - public int compare(IAEItemStack o1, IAEItemStack o2) + public int compare( IAEItemStack o1, IAEItemStack o2 ) { - if ( Direction == SortDir.ASCENDING ) + if( Direction == SortDir.ASCENDING ) return Platform.getItemDisplayName( o1 ).compareToIgnoreCase( Platform.getItemDisplayName( o2 ) ); return Platform.getItemDisplayName( o2 ).compareToIgnoreCase( Platform.getItemDisplayName( o1 ) ); } }; - - public static final Comparator CONFIG_BASED_SORT_BY_MOD = new Comparator() { + public static final Comparator CONFIG_BASED_SORT_BY_MOD = new Comparator() + { @Override - public int compare(IAEItemStack o1, IAEItemStack o2) + public int compare( IAEItemStack o1, IAEItemStack o2 ) { AEItemStack op1 = (AEItemStack) o1; AEItemStack op2 = (AEItemStack) o2; - if ( Direction == SortDir.ASCENDING ) + if( Direction == SortDir.ASCENDING ) return this.secondarySort( op2.getModID().compareToIgnoreCase( op1.getModID() ), o1, o2 ); return this.secondarySort( op1.getModID().compareToIgnoreCase( op2.getModID() ), o2, o1 ); } - private int secondarySort(int compareToIgnoreCase, IAEItemStack o1, IAEItemStack o2) + private int secondarySort( int compareToIgnoreCase, IAEItemStack o1, IAEItemStack o2 ) { - if ( compareToIgnoreCase == 0 ) + if( compareToIgnoreCase == 0 ) return Platform.getItemDisplayName( o2 ).compareToIgnoreCase( Platform.getItemDisplayName( o1 ) ); return compareToIgnoreCase; } }; - - public static final Comparator CONFIG_BASED_SORT_BY_SIZE = new Comparator() { + public static final Comparator CONFIG_BASED_SORT_BY_SIZE = new Comparator() + { @Override - public int compare(IAEItemStack o1, IAEItemStack o2) + public int compare( IAEItemStack o1, IAEItemStack o2 ) { - if ( Direction == SortDir.ASCENDING ) + if( Direction == SortDir.ASCENDING ) return compareLong( o2.getStackSize(), o1.getStackSize() ); return compareLong( o1.getStackSize(), o2.getStackSize() ); } }; - - public static final Comparator CONFIG_BASED_SORT_BY_INV_TWEAKS = new Comparator() { + private static IInvTweaks api; + public static final Comparator CONFIG_BASED_SORT_BY_INV_TWEAKS = new Comparator() + { @Override - public int compare(IAEItemStack o1, IAEItemStack o2) + public int compare( IAEItemStack o1, IAEItemStack o2 ) { - if ( api == null ) + if( api == null ) return CONFIG_BASED_SORT_BY_NAME.compare( o1, o2 ); int cmp = api.compareItems( o1.getItemStack(), o2.getItemStack() ); - if ( Direction == SortDir.ASCENDING ) + if( Direction == SortDir.ASCENDING ) return cmp; return -cmp; } }; + public static void init() + { + if( api != null ) + return; + + if( AppEng.instance.isIntegrationEnabled( IntegrationType.InvTweaks ) ) + api = (IInvTweaks) AppEng.instance.getIntegration( IntegrationType.InvTweaks ); + else + api = null; + } + + public static int compareInt( int a, int b ) + { + if( a == b ) + return 0; + if( a < b ) + return -1; + return 1; + } + + public static int compareLong( long a, long b ) + { + if( a == b ) + return 0; + if( a < b ) + return -1; + return 1; + } + + public static int compareDouble( double a, double b ) + { + if( a == b ) + return 0; + if( a < b ) + return -1; + return 1; + } } diff --git a/src/main/java/appeng/util/LookDirection.java b/src/main/java/appeng/util/LookDirection.java index 20e972404..2821db1f6 100644 --- a/src/main/java/appeng/util/LookDirection.java +++ b/src/main/java/appeng/util/LookDirection.java @@ -18,15 +18,18 @@ package appeng.util; + import net.minecraft.util.Vec3; + public class LookDirection { public final Vec3 a; public final Vec3 b; - public LookDirection(Vec3 a, Vec3 b) { + public LookDirection( Vec3 a, Vec3 b ) + { this.a = a; this.b = b; } diff --git a/src/main/java/appeng/util/Platform.java b/src/main/java/appeng/util/Platform.java index cae14a36c..fb578509b 100644 --- a/src/main/java/appeng/util/Platform.java +++ b/src/main/java/appeng/util/Platform.java @@ -139,6 +139,7 @@ import appeng.util.item.OreHelper; import appeng.util.item.OreReference; import appeng.util.prioitylist.IPartitionList; + public class Platform { @@ -150,17 +151,17 @@ public class Platform * random source, use it for item drop locations... */ static private final Random RANDOM_GENERATOR = new Random(); + private static final WeakHashMap FAKE_PLAYERS = new WeakHashMap(); + private static Field tagList; + private static Class playerInstance; + private static Method getOrCreateChunkWatcher; + private static Method sendToAllPlayersWatchingChunk; public static Random getRandom() { return RANDOM_GENERATOR; } - public static int getRandomInt() - { - return Math.abs( RANDOM_GENERATOR.nextInt() ); - } - public static float getRandomFloat() { return RANDOM_GENERATOR.nextFloat(); @@ -169,13 +170,14 @@ public class Platform /** * This displays the value for encoded longs ( double *100 ) * - * @param n to be formatted long value + * @param n to be formatted long value * @param isRate if true it adds a /t to the formatted string + * * @return formatted long value */ - public static String formatPowerLong(long n, boolean isRate) + public static String formatPowerLong( long n, boolean isRate ) { - double p = ((double) n) / 100; + double p = ( (double) n ) / 100; PowerUnits displayUnits = AEConfig.instance.selectedPowerUnit(); p = PowerUnits.AE.convertTo( displayUnits, p ); @@ -185,13 +187,13 @@ public class Platform String[] preFixes = new String[] { "k", "M", "G", "T", "P", "T", "P", "E", "Z", "Y" }; String unitName = displayUnits.name(); - if ( displayUnits == PowerUnits.WA ) + if( displayUnits == PowerUnits.WA ) unitName = "J"; - if ( displayUnits == PowerUnits.MK ) + if( displayUnits == PowerUnits.MK ) unitName = "J"; - while (p > 1000 && offset < preFixes.length) + while( p > 1000 && offset < preFixes.length ) { p /= 1000; Lvl = preFixes[offset]; @@ -199,54 +201,68 @@ public class Platform } DecimalFormat df = new DecimalFormat( "#.##" ); - return df.format( p ) + ' ' + Lvl + unitName + (isRate ? "/t" : ""); + return df.format( p ) + ' ' + Lvl + unitName + ( isRate ? "/t" : "" ); } - public static ForgeDirection crossProduct(ForgeDirection forward, ForgeDirection up) + public static ForgeDirection crossProduct( ForgeDirection forward, ForgeDirection up ) { int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - switch (west_x + west_y * 2 + west_z * 3) + switch( west_x + west_y * 2 + west_z * 3 ) { - case 1: - return ForgeDirection.EAST; - case -1: - return ForgeDirection.WEST; + case 1: + return ForgeDirection.EAST; + case -1: + return ForgeDirection.WEST; - case 2: - return ForgeDirection.UP; - case -2: - return ForgeDirection.DOWN; + case 2: + return ForgeDirection.UP; + case -2: + return ForgeDirection.DOWN; - case 3: - return ForgeDirection.SOUTH; - case -3: - return ForgeDirection.NORTH; + case 3: + return ForgeDirection.SOUTH; + case -3: + return ForgeDirection.NORTH; } return ForgeDirection.UNKNOWN; } + public static T rotateEnum( T ce, boolean backwards, EnumSet ValidOptions ) + { + do + { + if( backwards ) + ce = prevEnum( ce ); + else + ce = nextEnum( ce ); + } + while( !ValidOptions.contains( ce ) || isNotValidSetting( ce ) ); + + return ce; + } + /* * Simple way to cycle an enum... */ - public static T nextEnum(T ce) + public static T prevEnum( T ce ) { EnumSet valList = EnumSet.allOf( ce.getClass() ); - int pLoc = ce.ordinal() + 1; - if ( pLoc >= valList.size() ) - pLoc = 0; + int pLoc = ce.ordinal() - 1; + if( pLoc < 0 ) + pLoc = valList.size() - 1; - if ( pLoc < 0 || pLoc >= valList.size() ) + if( pLoc < 0 || pLoc >= valList.size() ) pLoc = 0; int pos = 0; - for (Object g : valList) + for( Object g : valList ) { - if ( pos == pLoc ) + if( pos == pLoc ) return (T) g; pos++; } @@ -254,57 +270,67 @@ public class Platform return null; } - public static T rotateEnum(T ce, boolean backwards, EnumSet ValidOptions) + /* + * Simple way to cycle an enum... + */ + public static T nextEnum( T ce ) { - do - { - if ( backwards ) - ce = prevEnum( ce ); - else - ce = nextEnum( ce ); - } - while (!ValidOptions.contains( ce ) || isNotValidSetting( ce )); + EnumSet valList = EnumSet.allOf( ce.getClass() ); - return ce; + int pLoc = ce.ordinal() + 1; + if( pLoc >= valList.size() ) + pLoc = 0; + + if( pLoc < 0 || pLoc >= valList.size() ) + pLoc = 0; + + int pos = 0; + for( Object g : valList ) + { + if( pos == pLoc ) + return (T) g; + pos++; + } + + return null; } - private static boolean isNotValidSetting(Enum e) + private static boolean isNotValidSetting( Enum e ) { - if ( e == SortOrder.INVTWEAKS && !AppEng.instance.isIntegrationEnabled( IntegrationType.InvTweaks ) ) + if( e == SortOrder.INVTWEAKS && !AppEng.instance.isIntegrationEnabled( IntegrationType.InvTweaks ) ) return true; - if ( e == SearchBoxMode.NEI_AUTOSEARCH && !AppEng.instance.isIntegrationEnabled( IntegrationType.NEI ) ) + if( e == SearchBoxMode.NEI_AUTOSEARCH && !AppEng.instance.isIntegrationEnabled( IntegrationType.NEI ) ) return true; - if ( e == SearchBoxMode.NEI_MANUAL_SEARCH && !AppEng.instance.isIntegrationEnabled( IntegrationType.NEI ) ) + if( e == SearchBoxMode.NEI_MANUAL_SEARCH && !AppEng.instance.isIntegrationEnabled( IntegrationType.NEI ) ) return true; return false; } - /* - * Simple way to cycle an enum... - */ - public static T prevEnum(T ce) + public static void openGUI( EntityPlayer p, TileEntity tile, ForgeDirection side, GuiBridge type ) { - EnumSet valList = EnumSet.allOf( ce.getClass() ); + if( isClient() ) + return; - int pLoc = ce.ordinal() - 1; - if ( pLoc < 0 ) - pLoc = valList.size() - 1; - - if ( pLoc < 0 || pLoc >= valList.size() ) - pLoc = 0; - - int pos = 0; - for (Object g : valList) + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if( tile != null ) { - if ( pos == pLoc ) - return (T) g; - pos++; + x = tile.xCoord; + y = tile.yCoord; + z = tile.zCoord; } - return null; + if( ( type.getType().isItem() && tile == null ) || type.hasPermissions( tile, x, y, z, side, p ) ) + { + if( tile == null || type.getType() == GuiHostType.ITEM ) + p.openGui( AppEng.instance, type.ordinal() << 4 | ( 1 << 3 ), p.getEntityWorld(), x, y, z ); + else + p.openGui( AppEng.instance, type.ordinal() << 4 | ( side.ordinal() ), tile.getWorldObj(), x, y, z ); + } } /* @@ -315,39 +341,7 @@ public class Platform return FMLCommonHandler.instance().getEffectiveSide().isClient(); } - /* - * returns true if the code is on the server. - */ - public static boolean isServer() - { - return FMLCommonHandler.instance().getEffectiveSide().isServer(); - } - - public static void openGUI(EntityPlayer p, TileEntity tile, ForgeDirection side, GuiBridge type) - { - if ( isClient() ) - return; - - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if ( tile != null ) - { - x = tile.xCoord; - y = tile.yCoord; - z = tile.zCoord; - } - - if ( (type.getType().isItem() && tile == null) || type.hasPermissions( tile, x, y, z, side, p ) ) - { - if ( tile == null || type.getType() == GuiHostType.ITEM ) - p.openGui( AppEng.instance, type.ordinal() << 4 | (1 << 3), p.getEntityWorld(), x, y, z ); - else - p.openGui( AppEng.instance, type.ordinal() << 4 | (side.ordinal()), tile.getWorldObj(), x, y, z ); - } - } - - public static boolean hasPermissions(DimensionalCoord dc, EntityPlayer player) + public static boolean hasPermissions( DimensionalCoord dc, EntityPlayer player ) { return dc.getWorld().canMineBlock( player, dc.x, dc.y, dc.z ); } @@ -355,13 +349,13 @@ public class Platform /* * Checks to see if a block is air? */ - public static boolean isBlockAir(World w, int x, int y, int z) + public static boolean isBlockAir( World w, int x, int y, int z ) { try { return w.getBlock( x, y, z ).isAir( w, x, y, z ); } - catch (Throwable e) + catch( Throwable e ) { return false; } @@ -371,29 +365,28 @@ public class Platform * Lots of silliness to try and account for weird tag related junk, basically requires that two tags have at least * something in their tags before it wasts its time comparing them. */ - public static boolean sameStackStags(ItemStack a, ItemStack b) + public static boolean sameStackStags( ItemStack a, ItemStack b ) { - if ( a == null && b == null ) + if( a == null && b == null ) return true; - if ( a == null || b == null ) + if( a == null || b == null ) return false; - if ( a == b ) + if( a == b ) return true; NBTTagCompound ta = a.getTagCompound(); NBTTagCompound tb = b.getTagCompound(); - if ( ta == tb ) + if( ta == tb ) return true; - if ( (ta == null && tb == null) || (ta != null && ta.hasNoTags() && tb == null) || (tb != null && tb.hasNoTags() && ta == null) - || (ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags()) ) + if( ( ta == null && tb == null ) || ( ta != null && ta.hasNoTags() && tb == null ) || ( tb != null && tb.hasNoTags() && ta == null ) || ( ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags() ) ) return true; - if ( (ta == null && tb != null) || (ta != null && tb == null) ) + if( ( ta == null && tb != null ) || ( ta != null && tb == null ) ) return false; // if both tags are shared this is easy... - if ( AESharedNBT.isShared( ta ) && AESharedNBT.isShared( tb ) ) + if( AESharedNBT.isShared( ta ) && AESharedNBT.isShared( tb ) ) { return ta == tb; } @@ -406,111 +399,108 @@ public class Platform * then the vanilla version which likes to fail when NBT Compound data changes order, it is pretty expensive * performance wise, so try an use shared tag compounds as long as the system remains in AE. */ - public static boolean NBTEqualityTest(NBTBase A, NBTBase B) + public static boolean NBTEqualityTest( NBTBase A, NBTBase B ) { // same type? byte id = A.getId(); - if ( id == B.getId() ) + if( id == B.getId() ) { - switch (id) + switch( id ) { - case 10: - { - NBTTagCompound ctA = (NBTTagCompound) A; - NBTTagCompound ctB = (NBTTagCompound) B; - - Set cA = ctA.func_150296_c(); - Set cB = ctB.func_150296_c(); - - if ( cA.size() != cB.size() ) - return false; - - for (String name : cA) + case 10: { - NBTBase tag = ctA.getTag( name ); - NBTBase aTag = ctB.getTag( name ); - if ( aTag == null ) - { + NBTTagCompound ctA = (NBTTagCompound) A; + NBTTagCompound ctB = (NBTTagCompound) B; + + Set cA = ctA.func_150296_c(); + Set cB = ctB.func_150296_c(); + + if( cA.size() != cB.size() ) return false; + + for( String name : cA ) + { + NBTBase tag = ctA.getTag( name ); + NBTBase aTag = ctB.getTag( name ); + if( aTag == null ) + { + return false; + } + + if( !NBTEqualityTest( tag, aTag ) ) + { + return false; + } } - if ( !NBTEqualityTest( tag, aTag ) ) - { - return false; - } + return true; } - return true; - } - - case 9: // ) // A instanceof NBTTagList ) - { - NBTTagList lA = (NBTTagList) A; - NBTTagList lB = (NBTTagList) B; - if ( lA.tagCount() != lB.tagCount() ) - return false; - - List tag = tagList( lA ); - List aTag = tagList( lB ); - if ( tag.size() != aTag.size() ) - return false; - - for (int x = 0; x < tag.size(); x++) + case 9: // ) // A instanceof NBTTagList ) { - if ( aTag.get( x ) == null ) + NBTTagList lA = (NBTTagList) A; + NBTTagList lB = (NBTTagList) B; + if( lA.tagCount() != lB.tagCount() ) return false; - if ( !NBTEqualityTest( tag.get( x ), aTag.get( x ) ) ) + List tag = tagList( lA ); + List aTag = tagList( lB ); + if( tag.size() != aTag.size() ) return false; + + for( int x = 0; x < tag.size(); x++ ) + { + if( aTag.get( x ) == null ) + return false; + + if( !NBTEqualityTest( tag.get( x ), aTag.get( x ) ) ) + return false; + } + + return true; } - return true; - } + case 1: // ( A instanceof NBTTagByte ) + return ( (NBTTagByte) A ).func_150287_d() == ( (NBTTagByte) B ).func_150287_d(); - case 1: // ( A instanceof NBTTagByte ) - return ((NBTTagByte) A).func_150287_d() == ((NBTTagByte) B).func_150287_d(); + case 4: // else if ( A instanceof NBTTagLong ) + return ( (NBTTagLong) A ).func_150291_c() == ( (NBTTagLong) B ).func_150291_c(); - case 4: // else if ( A instanceof NBTTagLong ) - return ((NBTTagLong) A).func_150291_c() == ((NBTTagLong) B).func_150291_c(); + case 8: // else if ( A instanceof NBTTagString ) + return ( (NBTTagString) A ).func_150285_a_().equals( ( (NBTTagString) B ).func_150285_a_() ) || ( (NBTTagString) A ).func_150285_a_().equals( ( (NBTTagString) B ).func_150285_a_() ); - case 8: // else if ( A instanceof NBTTagString ) - return ((NBTTagString) A).func_150285_a_().equals( ((NBTTagString) B).func_150285_a_() ) - || ((NBTTagString) A).func_150285_a_().equals( ((NBTTagString) B).func_150285_a_() ); + case 6: // else if ( A instanceof NBTTagDouble ) + return ( (NBTTagDouble) A ).func_150286_g() == ( (NBTTagDouble) B ).func_150286_g(); - case 6: // else if ( A instanceof NBTTagDouble ) - return ((NBTTagDouble) A).func_150286_g() == ((NBTTagDouble) B).func_150286_g(); + case 5: // else if ( A instanceof NBTTagFloat ) + return ( (NBTTagFloat) A ).func_150288_h() == ( (NBTTagFloat) B ).func_150288_h(); - case 5: // else if ( A instanceof NBTTagFloat ) - return ((NBTTagFloat) A).func_150288_h() == ((NBTTagFloat) B).func_150288_h(); + case 3: // else if ( A instanceof NBTTagInt ) + return ( (NBTTagInt) A ).func_150287_d() == ( (NBTTagInt) B ).func_150287_d(); - case 3: // else if ( A instanceof NBTTagInt ) - return ((NBTTagInt) A).func_150287_d() == ((NBTTagInt) B).func_150287_d(); - - default: - return A.equals( B ); + default: + return A.equals( B ); } } return false; } - private static Field tagList; - - private static List tagList(NBTTagList lB) + private static List tagList( NBTTagList lB ) { - if ( tagList == null ) + if( tagList == null ) { try { tagList = lB.getClass().getDeclaredField( "tagList" ); } - catch (Throwable t) + catch( Throwable t ) { try { tagList = lB.getClass().getDeclaredField( "field_74747_a" ); } - catch (Throwable z) + catch( Throwable z ) { AELog.error( t ); AELog.error( z ); @@ -523,7 +513,7 @@ public class Platform tagList.setAccessible( true ); return (List) tagList.get( lB ); } - catch (Throwable t) + catch( Throwable t ) { AELog.error( t ); } @@ -535,76 +525,76 @@ public class Platform * Orderless hash on NBT Data, used to work thought huge piles fast, but ignores the order just in case MC decided * to change it... WHICH IS BAD... */ - public static int NBTOrderlessHash(NBTBase A) + public static int NBTOrderlessHash( NBTBase A ) { // same type? int hash = 0; byte id = A.getId(); hash += id; - switch (id) + switch( id ) { - case 10: - { - NBTTagCompound ctA = (NBTTagCompound) A; - - Set cA = ctA.func_150296_c(); - - for (String name : cA) + case 10: { - hash += name.hashCode() ^ NBTOrderlessHash( ctA.getTag( name ) ); + NBTTagCompound ctA = (NBTTagCompound) A; + + Set cA = ctA.func_150296_c(); + + for( String name : cA ) + { + hash += name.hashCode() ^ NBTOrderlessHash( ctA.getTag( name ) ); + } + + return hash; } - return hash; - } - - case 9: // ) // A instanceof NBTTagList ) - { - NBTTagList lA = (NBTTagList) A; - hash += 9 * lA.tagCount(); - - List l = tagList( lA ); - for (int x = 0; x < l.size(); x++) + case 9: // ) // A instanceof NBTTagList ) { - hash += ((Integer) x).hashCode() ^ NBTOrderlessHash( l.get( x ) ); + NBTTagList lA = (NBTTagList) A; + hash += 9 * lA.tagCount(); + + List l = tagList( lA ); + for( int x = 0; x < l.size(); x++ ) + { + hash += ( (Integer) x ).hashCode() ^ NBTOrderlessHash( l.get( x ) ); + } + + return hash; } - return hash; - } + case 1: // ( A instanceof NBTTagByte ) + return hash + ( (NBTTagByte) A ).func_150290_f(); - case 1: // ( A instanceof NBTTagByte ) - return hash + ((NBTTagByte) A).func_150290_f(); + case 4: // else if ( A instanceof NBTTagLong ) + return hash + (int) ( (NBTTagLong) A ).func_150291_c(); - case 4: // else if ( A instanceof NBTTagLong ) - return hash + (int) ((NBTTagLong) A).func_150291_c(); + case 8: // else if ( A instanceof NBTTagString ) + return hash + ( (NBTTagString) A ).func_150285_a_().hashCode(); - case 8: // else if ( A instanceof NBTTagString ) - return hash + ((NBTTagString) A).func_150285_a_().hashCode(); + case 6: // else if ( A instanceof NBTTagDouble ) + return hash + (int) ( (NBTTagDouble) A ).func_150286_g(); - case 6: // else if ( A instanceof NBTTagDouble ) - return hash + (int) ((NBTTagDouble) A).func_150286_g(); + case 5: // else if ( A instanceof NBTTagFloat ) + return hash + (int) ( (NBTTagFloat) A ).func_150288_h(); - case 5: // else if ( A instanceof NBTTagFloat ) - return hash + (int) ((NBTTagFloat) A).func_150288_h(); + case 3: // else if ( A instanceof NBTTagInt ) + return hash + ( (NBTTagInt) A ).func_150287_d(); - case 3: // else if ( A instanceof NBTTagInt ) - return hash + ((NBTTagInt) A).func_150287_d(); - - default: - return hash; + default: + return hash; } } /* * The usual version of this returns an ItemStack, this version returns the recipe. */ - public static IRecipe findMatchingRecipe(InventoryCrafting par1InventoryCrafting, World par2World) + public static IRecipe findMatchingRecipe( InventoryCrafting par1InventoryCrafting, World par2World ) { CraftingManager cm = CraftingManager.getInstance(); List rl = cm.getRecipeList(); - for (IRecipe r : rl) + for( IRecipe r : rl ) { - if ( r.matches( par1InventoryCrafting, par2World ) ) + if( r.matches( par1InventoryCrafting, par2World ) ) { return r; } @@ -613,61 +603,61 @@ public class Platform return null; } - public static ItemStack[] getBlockDrops(World w, int x, int y, int z) + public static ItemStack[] getBlockDrops( World w, int x, int y, int z ) { List out = new ArrayList(); Block which = w.getBlock( x, y, z ); - if ( which != null ) + if( which != null ) { out = which.getDrops( w, x, y, z, w.getBlockMetadata( x, y, z ), 0 ); } - if ( out == null ) + if( out == null ) return new ItemStack[0]; return out.toArray( new ItemStack[out.size()] ); } - public static ForgeDirection cycleOrientations(ForgeDirection dir, boolean upAndDown) + public static ForgeDirection cycleOrientations( ForgeDirection dir, boolean upAndDown ) { - if ( upAndDown ) + if( upAndDown ) { - switch (dir) + switch( dir ) { - case NORTH: - return ForgeDirection.SOUTH; - case SOUTH: - return ForgeDirection.EAST; - case EAST: - return ForgeDirection.WEST; - case WEST: - return ForgeDirection.NORTH; - case UP: - return ForgeDirection.UP; - case DOWN: - return ForgeDirection.DOWN; - case UNKNOWN: - return ForgeDirection.UNKNOWN; + case NORTH: + return ForgeDirection.SOUTH; + case SOUTH: + return ForgeDirection.EAST; + case EAST: + return ForgeDirection.WEST; + case WEST: + return ForgeDirection.NORTH; + case UP: + return ForgeDirection.UP; + case DOWN: + return ForgeDirection.DOWN; + case UNKNOWN: + return ForgeDirection.UNKNOWN; } } else { - switch (dir) + switch( dir ) { - case UP: - return ForgeDirection.DOWN; - case DOWN: - return ForgeDirection.NORTH; - case NORTH: - return ForgeDirection.SOUTH; - case SOUTH: - return ForgeDirection.EAST; - case EAST: - return ForgeDirection.WEST; - case WEST: - return ForgeDirection.UP; - case UNKNOWN: - return ForgeDirection.UNKNOWN; + case UP: + return ForgeDirection.DOWN; + case DOWN: + return ForgeDirection.NORTH; + case NORTH: + return ForgeDirection.SOUTH; + case SOUTH: + return ForgeDirection.EAST; + case EAST: + return ForgeDirection.WEST; + case WEST: + return ForgeDirection.UP; + case UNKNOWN: + return ForgeDirection.UNKNOWN; } } @@ -677,11 +667,11 @@ public class Platform /* * Creates / or loads previous NBT Data on items, used for editing items owned by AE. */ - public static NBTTagCompound openNbtData(ItemStack i) + public static NBTTagCompound openNbtData( ItemStack i ) { NBTTagCompound compound = i.getTagCompound(); - if ( compound == null ) + if( compound == null ) { i.setTagCompound( compound = new NBTTagCompound() ); } @@ -692,19 +682,19 @@ public class Platform /* * Generates Item entities in the world similar to how items are generally dropped. */ - public static void spawnDrops(World w, int x, int y, int z, List drops) + public static void spawnDrops( World w, int x, int y, int z, List drops ) { - if ( isServer() ) + if( isServer() ) { - for (ItemStack i : drops) + for( ItemStack i : drops ) { - if ( i != null ) + if( i != null ) { - if ( i.stackSize > 0 ) + if( i.stackSize > 0 ) { - double offset_x = (getRandomInt() % 32 - 16) / 82; - double offset_y = (getRandomInt() % 32 - 16) / 82; - double offset_z = (getRandomInt() % 32 - 16) / 82; + double offset_x = ( getRandomInt() % 32 - 16 ) / 82; + double offset_y = ( getRandomInt() % 32 - 16 ) / 82; + double offset_z = ( getRandomInt() % 32 - 16 ) / 82; EntityItem ei = new EntityItem( w, 0.5 + offset_x + x, 0.5 + offset_y + y, 0.2 + offset_z + z, i.copy() ); w.spawnEntityInWorld( ei ); } @@ -713,28 +703,41 @@ public class Platform } } + /* + * returns true if the code is on the server. + */ + public static boolean isServer() + { + return FMLCommonHandler.instance().getEffectiveSide().isServer(); + } + + public static int getRandomInt() + { + return Math.abs( RANDOM_GENERATOR.nextInt() ); + } + /* * Utility function to get the full inventory for a Double Chest in the World. */ - public static IInventory GetChestInv(Object te) + public static IInventory GetChestInv( Object te ) { TileEntityChest teA = (TileEntityChest) te; TileEntity teB = null; Block myBlockID = teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord ); - if ( teA.getWorldObj().getBlock( teA.xCoord + 1, teA.yCoord, teA.zCoord ) == myBlockID ) + if( teA.getWorldObj().getBlock( teA.xCoord + 1, teA.yCoord, teA.zCoord ) == myBlockID ) { teB = teA.getWorldObj().getTileEntity( teA.xCoord + 1, teA.yCoord, teA.zCoord ); - if ( !(teB instanceof TileEntityChest) ) + if( !( teB instanceof TileEntityChest ) ) teB = null; } - if ( teB == null ) + if( teB == null ) { - if ( teA.getWorldObj().getBlock( teA.xCoord - 1, teA.yCoord, teA.zCoord ) == myBlockID ) + if( teA.getWorldObj().getBlock( teA.xCoord - 1, teA.yCoord, teA.zCoord ) == myBlockID ) { teB = teA.getWorldObj().getTileEntity( teA.xCoord - 1, teA.yCoord, teA.zCoord ); - if ( !(teB instanceof TileEntityChest) ) + if( !( teB instanceof TileEntityChest ) ) teB = null; else { @@ -745,22 +748,22 @@ public class Platform } } - if ( teB == null ) + if( teB == null ) { - if ( teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord + 1 ) == myBlockID ) + if( teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord + 1 ) == myBlockID ) { teB = teA.getWorldObj().getTileEntity( teA.xCoord, teA.yCoord, teA.zCoord + 1 ); - if ( !(teB instanceof TileEntityChest) ) + if( !( teB instanceof TileEntityChest ) ) teB = null; } } - if ( teB == null ) + if( teB == null ) { - if ( teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord - 1 ) == myBlockID ) + if( teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord - 1 ) == myBlockID ) { teB = teA.getWorldObj().getTileEntity( teA.xCoord, teA.yCoord, teA.zCoord - 1 ); - if ( !(teB instanceof TileEntityChest) ) + if( !( teB instanceof TileEntityChest ) ) teB = null; else { @@ -771,26 +774,26 @@ public class Platform } } - if ( teB == null ) + if( teB == null ) return teA; return new InventoryLargeChest( "", teA, (TileEntityChest) teB ); } - public static boolean isModLoaded(String modid) + public static boolean isModLoaded( String modid ) { try { // if this fails for some reason, try the other method. return Loader.isModLoaded( modid ); } - catch (Throwable ignored) + catch( Throwable ignored ) { } - for (ModContainer f : Loader.instance().getActiveModList()) + for( ModContainer f : Loader.instance().getActiveModList() ) { - if ( f.getModId().equals( modid ) ) + if( f.getModId().equals( modid ) ) { return true; } @@ -798,24 +801,24 @@ public class Platform return false; } - public static ItemStack findMatchingRecipeOutput(InventoryCrafting ic, World worldObj) + public static ItemStack findMatchingRecipeOutput( InventoryCrafting ic, World worldObj ) { return CraftingManager.getInstance().findMatchingRecipe( ic, worldObj ); } - @SideOnly(Side.CLIENT) - public static List getTooltip(Object o) + @SideOnly( Side.CLIENT ) + public static List getTooltip( Object o ) { - if ( o == null ) + if( o == null ) return new ArrayList(); ItemStack itemStack = null; - if ( o instanceof AEItemStack ) + if( o instanceof AEItemStack ) { AEItemStack ais = (AEItemStack) o; return ais.getToolTip(); } - else if ( o instanceof ItemStack ) + else if( o instanceof ItemStack ) itemStack = (ItemStack) o; else return new ArrayList(); @@ -824,33 +827,33 @@ public class Platform { return itemStack.getTooltip( Minecraft.getMinecraft().thePlayer, false ); } - catch (Exception errB) + catch( Exception errB ) { return new ArrayList(); } } - public static String getModId(IAEItemStack is) + public static String getModId( IAEItemStack is ) { - if ( is == null ) + if( is == null ) return "** Null"; - String n = ((AEItemStack) is).getModID(); + String n = ( (AEItemStack) is ).getModID(); return n == null ? "** Null" : n; } - public static String getItemDisplayName(Object o) + public static String getItemDisplayName( Object o ) { - if ( o == null ) + if( o == null ) return "** Null"; ItemStack itemStack = null; - if ( o instanceof AEItemStack ) + if( o instanceof AEItemStack ) { - String n = ((AEItemStack) o).getDisplayName(); + String n = ( (AEItemStack) o ).getDisplayName(); return n == null ? "** Null" : n; } - else if ( o instanceof ItemStack ) + else if( o instanceof ItemStack ) itemStack = (ItemStack) o; else return "**Invalid Object"; @@ -858,62 +861,62 @@ public class Platform try { String name = itemStack.getDisplayName(); - if ( name == null || name.isEmpty() ) + if( name == null || name.isEmpty() ) name = itemStack.getItem().getUnlocalizedName( itemStack ); return name == null ? "** Null" : name; } - catch (Exception errA) + catch( Exception errA ) { try { String n = itemStack.getUnlocalizedName(); return n == null ? "** Null" : n; } - catch (Exception errB) + catch( Exception errB ) { return "** Exception"; } } } - public static boolean hasSpecialComparison(IAEItemStack willAdd) + public static boolean hasSpecialComparison( IAEItemStack willAdd ) { - if ( willAdd == null ) + if( willAdd == null ) return false; IAETagCompound tag = willAdd.getTagCompound(); - if ( tag != null && tag.getSpecialComparison() != null ) + if( tag != null && tag.getSpecialComparison() != null ) return true; return false; } - public static boolean hasSpecialComparison(ItemStack willAdd) + public static boolean hasSpecialComparison( ItemStack willAdd ) { - if ( AESharedNBT.isShared( willAdd.getTagCompound() ) ) + if( AESharedNBT.isShared( willAdd.getTagCompound() ) ) { - if ( ((AESharedNBT) willAdd.getTagCompound()).getSpecialComparison() != null ) + if( ( (AESharedNBT) willAdd.getTagCompound() ).getSpecialComparison() != null ) return true; } return false; } - public static boolean isWrench(EntityPlayer player, ItemStack eq, int x, int y, int z) + public static boolean isWrench( EntityPlayer player, ItemStack eq, int x, int y, int z ) { - if ( eq != null ) + if( eq != null ) { try { - if ( eq.getItem() instanceof IToolWrench ) + if( eq.getItem() instanceof IToolWrench ) { IToolWrench wrench = (IToolWrench) eq.getItem(); return wrench.canWrench( player, x, y, z ); } } - catch (Throwable ignore) + catch( Throwable ignore ) { // explodes without BC } - if ( eq.getItem() instanceof IAEWrench ) + if( eq.getItem() instanceof IAEWrench ) { IAEWrench wrench = (IAEWrench) eq.getItem(); return wrench.canWrench( eq, player, x, y, z ); @@ -922,27 +925,25 @@ public class Platform return false; } - public static boolean isChargeable(ItemStack i) + public static boolean isChargeable( ItemStack i ) { - if ( i == null ) + if( i == null ) return false; Item it = i.getItem(); - if ( it instanceof IAEItemPowerStorage ) + if( it instanceof IAEItemPowerStorage ) { - return ((IAEItemPowerStorage) it).getPowerFlow( i ) != AccessRestriction.READ; + return ( (IAEItemPowerStorage) it ).getPowerFlow( i ) != AccessRestriction.READ; } return false; } - private static final WeakHashMap FAKE_PLAYERS = new WeakHashMap(); - - public static EntityPlayer getPlayer(WorldServer w) + public static EntityPlayer getPlayer( WorldServer w ) { - if ( w == null ) + if( w == null ) throw new NullPointerException(); EntityPlayer wrp = FAKE_PLAYERS.get( w ); - if ( wrp != null ) + if( wrp != null ) return wrp; EntityPlayer p = FakePlayerFactory.getMinecraft( w ); @@ -950,216 +951,192 @@ public class Platform return p; } - public static int MC2MEColor(int color) + public static int MC2MEColor( int color ) { - switch (color) + switch( color ) { - case 4: // "blue" - return 0; - case 0: // "black" - return 1; - case 15: // "white" - return 2; - case 3: // "brown" - return 3; - case 1: // "red" - return 4; - case 11: // "yellow" - return 5; - case 2: // "green" - return 6; - - case 5: // "purple" - case 6: // "cyan" - case 7: // "silver" - case 8: // "gray" - case 9: // "pink" - case 10: // "lime" - case 12: // "lightBlue" - case 13: // "magenta" - case 14: // "orange" + case 4: // "blue" + return 0; + case 0: // "black" + return 1; + case 15: // "white" + return 2; + case 3: // "brown" + return 3; + case 1: // "red" + return 4; + case 11: // "yellow" + return 5; + case 2: // "green" + return 6; + case 5: // "purple" + case 6: // "cyan" + case 7: // "silver" + case 8: // "gray" + case 9: // "pink" + case 10: // "lime" + case 12: // "lightBlue" + case 13: // "magenta" + case 14: // "orange" } return -1; } - public static int findEmpty(Object[] l) + public static int findEmpty( Object[] l ) { - for (int x = 0; x < l.length; x++) + for( int x = 0; x < l.length; x++ ) { - if ( l[x] == null ) + if( l[x] == null ) return x; } return -1; } - public static T pickRandom(Collection outs) + public static T pickRandom( Collection outs ) { int index = RANDOM_GENERATOR.nextInt( outs.size() ); Iterator i = outs.iterator(); - while (i.hasNext() && index > 0) + while( i.hasNext() && index > 0 ) { index--; i.next(); } index--; - if ( i.hasNext() ) + if( i.hasNext() ) return i.next(); return null; // wtf? } - - - public static ForgeDirection rotateAround(ForgeDirection forward, ForgeDirection axis) + public static ForgeDirection rotateAround( ForgeDirection forward, ForgeDirection axis ) { - if ( axis == ForgeDirection.UNKNOWN || forward == ForgeDirection.UNKNOWN ) + if( axis == ForgeDirection.UNKNOWN || forward == ForgeDirection.UNKNOWN ) return forward; - switch (forward) + switch( forward ) { - case DOWN: - switch (axis) - { case DOWN: - return forward; + switch( axis ) + { + case DOWN: + return forward; + case UP: + return forward; + case NORTH: + return ForgeDirection.EAST; + case SOUTH: + return ForgeDirection.WEST; + case EAST: + return ForgeDirection.NORTH; + case WEST: + return ForgeDirection.SOUTH; + default: + break; + } + break; case UP: - return forward; + switch( axis ) + { + case NORTH: + return ForgeDirection.WEST; + case SOUTH: + return ForgeDirection.EAST; + case EAST: + return ForgeDirection.SOUTH; + case WEST: + return ForgeDirection.NORTH; + default: + break; + } + break; case NORTH: - return ForgeDirection.EAST; + switch( axis ) + { + case UP: + return ForgeDirection.WEST; + case DOWN: + return ForgeDirection.EAST; + case EAST: + return ForgeDirection.UP; + case WEST: + return ForgeDirection.DOWN; + default: + break; + } + break; case SOUTH: - return ForgeDirection.WEST; + switch( axis ) + { + case UP: + return ForgeDirection.EAST; + case DOWN: + return ForgeDirection.WEST; + case EAST: + return ForgeDirection.DOWN; + case WEST: + return ForgeDirection.UP; + default: + break; + } + break; case EAST: - return ForgeDirection.NORTH; + switch( axis ) + { + case UP: + return ForgeDirection.NORTH; + case DOWN: + return ForgeDirection.SOUTH; + case NORTH: + return ForgeDirection.UP; + case SOUTH: + return ForgeDirection.DOWN; + default: + break; + } case WEST: - return ForgeDirection.SOUTH; + switch( axis ) + { + case UP: + return ForgeDirection.SOUTH; + case DOWN: + return ForgeDirection.NORTH; + case NORTH: + return ForgeDirection.DOWN; + case SOUTH: + return ForgeDirection.UP; + default: + break; + } default: break; - } - break; - case UP: - switch (axis) - { - case NORTH: - return ForgeDirection.WEST; - case SOUTH: - return ForgeDirection.EAST; - case EAST: - return ForgeDirection.SOUTH; - case WEST: - return ForgeDirection.NORTH; - default: - break; - } - break; - case NORTH: - switch (axis) - { - case UP: - return ForgeDirection.WEST; - case DOWN: - return ForgeDirection.EAST; - case EAST: - return ForgeDirection.UP; - case WEST: - return ForgeDirection.DOWN; - default: - break; - } - break; - case SOUTH: - switch (axis) - { - case UP: - return ForgeDirection.EAST; - case DOWN: - return ForgeDirection.WEST; - case EAST: - return ForgeDirection.DOWN; - case WEST: - return ForgeDirection.UP; - default: - break; - } - break; - case EAST: - switch (axis) - { - case UP: - return ForgeDirection.NORTH; - case DOWN: - return ForgeDirection.SOUTH; - case NORTH: - return ForgeDirection.UP; - case SOUTH: - return ForgeDirection.DOWN; - default: - break; - } - case WEST: - switch (axis) - { - case UP: - return ForgeDirection.SOUTH; - case DOWN: - return ForgeDirection.NORTH; - case NORTH: - return ForgeDirection.DOWN; - case SOUTH: - return ForgeDirection.UP; - default: - break; - } - default: - break; } return forward; } - @SideOnly(Side.CLIENT) - public static String gui_localize(String string) + @SideOnly( Side.CLIENT ) + public static String gui_localize( String string ) { return StatCollector.translateToLocal( string ); } - public static boolean isSameItemType(ItemStack ol, ItemStack op) - { - if ( ol != null && op != null && ol.getItem() == op.getItem() ) - { - if ( ol.isItemStackDamageable() ) - return true; - return ol.getItemDamage() == ol.getItemDamage(); - } - return false; - } - - public static boolean isSameItem(ItemStack left, ItemStack right) - { - return left != null && right != null && left.isItemEqual( right ); - } - - public static ItemStack cloneItemStack(ItemStack a) - { - return a.copy(); - } - - public static boolean isSameItemPrecise(ItemStack is, ItemStack filter) + public static boolean isSameItemPrecise( ItemStack is, ItemStack filter ) { return isSameItem( is, filter ) && sameStackStags( is, filter ); } - public static boolean isSameItemFuzzy(ItemStack a, ItemStack b, FuzzyMode Mode) + public static boolean isSameItemFuzzy( ItemStack a, ItemStack b, FuzzyMode Mode ) { - if ( a == null && b == null ) + if( a == null && b == null ) { return true; } - if ( a == null ) + if( a == null ) { return false; } - if ( b == null ) + if( b == null ) { return false; } @@ -1170,42 +1147,42 @@ public class Platform */ // test damageable items.. - if ( a.getItem() != null && b.getItem() != null && a.getItem().isDamageable() && a.getItem() == b.getItem() ) + if( a.getItem() != null && b.getItem() != null && a.getItem().isDamageable() && a.getItem() == b.getItem() ) { try { - if ( Mode == FuzzyMode.IGNORE_ALL ) + if( Mode == FuzzyMode.IGNORE_ALL ) { return true; } - else if ( Mode == FuzzyMode.PERCENT_99 ) + else if( Mode == FuzzyMode.PERCENT_99 ) { - return (a.getItemDamageForDisplay() > 1) == (b.getItemDamageForDisplay() > 1); + return ( a.getItemDamageForDisplay() > 1 ) == ( b.getItemDamageForDisplay() > 1 ); } else { float APercentDamaged = 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); float BPercentDamaged = 1.0f - (float) b.getItemDamageForDisplay() / (float) b.getMaxDamage(); - return (APercentDamaged > Mode.breakPoint) == (BPercentDamaged > Mode.breakPoint); + return ( APercentDamaged > Mode.breakPoint ) == ( BPercentDamaged > Mode.breakPoint ); } } - catch (Throwable e) + catch( Throwable e ) { - if ( Mode == FuzzyMode.IGNORE_ALL ) + if( Mode == FuzzyMode.IGNORE_ALL ) { return true; } - else if ( Mode == FuzzyMode.PERCENT_99 ) + else if( Mode == FuzzyMode.PERCENT_99 ) { - return (a.getItemDamage() > 1) == (b.getItemDamage() > 1); + return ( a.getItemDamage() > 1 ) == ( b.getItemDamage() > 1 ); } else { float APercentDamaged = (float) a.getItemDamage() / (float) a.getMaxDamage(); float BPercentDamaged = (float) b.getItemDamage() / (float) b.getMaxDamage(); - return (APercentDamaged > Mode.breakPoint) == (BPercentDamaged > Mode.breakPoint); + return ( APercentDamaged > Mode.breakPoint ) == ( BPercentDamaged > Mode.breakPoint ); } } } @@ -1213,7 +1190,7 @@ public class Platform OreReference aOR = OreHelper.INSTANCE.isOre( a ); OreReference bOR = OreHelper.INSTANCE.isOre( b ); - if ( OreHelper.INSTANCE.sameOre( aOR, bOR ) ) + if( OreHelper.INSTANCE.sameOre( aOR, bOR ) ) return true; /* @@ -1233,14 +1210,14 @@ public class Platform return a.isItemEqual( b ); } - public static LookDirection getPlayerRay(EntityPlayer player, float eyeOffset) + public static LookDirection getPlayerRay( EntityPlayer player, float eyeOffset ) { float f = 1.0F; - float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f; - float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; - double d0 = player.prevPosX + (player.posX - player.prevPosX) * f; + float f1 = player.prevRotationPitch + ( player.rotationPitch - player.prevRotationPitch ) * f; + float f2 = player.prevRotationYaw + ( player.rotationYaw - player.prevRotationYaw ) * f; + double d0 = player.prevPosX + ( player.posX - player.prevPosX ) * f; double d1 = eyeOffset; - double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * f; + double d2 = player.prevPosZ + ( player.posZ - player.prevPosZ ) * f; Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); @@ -1251,24 +1228,24 @@ public class Platform float f8 = f3 * f5; double d3 = 5.0D; - if ( player instanceof EntityPlayerMP ) + if( player instanceof EntityPlayerMP ) { - d3 = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance(); + d3 = ( (EntityPlayerMP) player ).theItemInWorldManager.getBlockReachDistance(); } Vec3 vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); return new LookDirection( vec3, vec31 ); } - public static MovingObjectPosition rayTrace(EntityPlayer p, boolean hitBlocks, boolean hitEntities) + public static MovingObjectPosition rayTrace( EntityPlayer p, boolean hitBlocks, boolean hitEntities ) { World w = p.getEntityWorld(); float f = 1.0F; - float f1 = p.prevRotationPitch + (p.rotationPitch - p.prevRotationPitch) * f; - float f2 = p.prevRotationYaw + (p.rotationYaw - p.prevRotationYaw) * f; - double d0 = p.prevPosX + (p.posX - p.prevPosX) * f; - double d1 = p.prevPosY + (p.posY - p.prevPosY) * f + 1.62D - p.yOffset; - double d2 = p.prevPosZ + (p.posZ - p.prevPosZ) * f; + float f1 = p.prevRotationPitch + ( p.rotationPitch - p.prevRotationPitch ) * f; + float f2 = p.prevRotationYaw + ( p.rotationYaw - p.prevRotationYaw ) * f; + double d0 = p.prevPosX + ( p.posX - p.prevPosX ) * f; + double d1 = p.prevPosY + ( p.posY - p.prevPosY ) * f + 1.62D - p.yOffset; + double d2 = p.prevPosZ + ( p.posZ - p.prevPosZ ) * f; Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); @@ -1280,38 +1257,36 @@ public class Platform Vec3 vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); - AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), - Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), - Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); + AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); Entity entity = null; double closest = 9999999.0D; - if ( hitEntities ) + if( hitEntities ) { List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); int l; - for (l = 0; l < list.size(); ++l) + for( l = 0; l < list.size(); ++l ) { Entity entity1 = (Entity) list.get( l ); - if ( !entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem) ) + if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) { - if ( entity1.isEntityAlive() ) + if( entity1.isEntityAlive() ) { // prevent killing / flying of mounts. - if ( entity1.riddenByEntity == p ) + if( entity1.riddenByEntity == p ) continue; f1 = 0.3F; AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); - if ( movingObjectPosition != null ) + if( movingObjectPosition != null ) { double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); - if ( nd < closest ) + if( nd < closest ) { entity = entity1; closest = nd; @@ -1325,17 +1300,17 @@ public class Platform MovingObjectPosition pos = null; Vec3 vec = null; - if ( hitBlocks ) + if( hitBlocks ) { vec = Vec3.createVectorHelper( d0, d1, d2 ); pos = w.rayTraceBlocks( vec3, vec31, true ); } - if ( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) + if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) { pos = new MovingObjectPosition( entity ); } - else if ( entity != null && pos == null ) + else if( entity != null && pos == null ) { pos = new MovingObjectPosition( entity ); } @@ -1350,29 +1325,28 @@ public class Platform return 0; } - public static StackType poweredExtraction(IEnergySource energy, IMEInventory cell, StackType request, - BaseActionSource src) + public static StackType poweredExtraction( IEnergySource energy, IMEInventory cell, StackType request, BaseActionSource src ) { StackType possible = cell.extractItems( (StackType) request.copy(), Actionable.SIMULATE, src ); long retrieved = 0; - if ( possible != null ) + if( possible != null ) retrieved = possible.getStackSize(); double availablePower = energy.extractAEPower( retrieved, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - long itemToExtract = Math.min( (long) (availablePower + 0.9), retrieved ); + long itemToExtract = Math.min( (long) ( availablePower + 0.9 ), retrieved ); - if ( itemToExtract > 0 ) + if( itemToExtract > 0 ) { energy.extractAEPower( retrieved, Actionable.MODULATE, PowerMultiplier.CONFIG ); possible.setStackSize( itemToExtract ); StackType ret = cell.extractItems( possible, Actionable.MODULATE, src ); - if ( ret != null && src.isPlayer() ) + if( ret != null && src.isPlayer() ) { - Stats.ItemsExtracted.addToPlayer( ((PlayerSource) src).player, (int) ret.getStackSize() ); + Stats.ItemsExtracted.addToPlayer( ( (PlayerSource) src ).player, (int) ret.getStackSize() ); } return ret; @@ -1381,23 +1355,23 @@ public class Platform return null; } - public static StackType poweredInsert(IEnergySource energy, IMEInventory cell, StackType input, BaseActionSource src) + public static StackType poweredInsert( IEnergySource energy, IMEInventory cell, StackType input, BaseActionSource src ) { StackType possible = cell.injectItems( (StackType) input.copy(), Actionable.SIMULATE, src ); long stored = input.getStackSize(); - if ( possible != null ) + if( possible != null ) stored -= possible.getStackSize(); double availablePower = energy.extractAEPower( stored, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - long itemToAdd = Math.min( (long) (availablePower + 0.9), stored ); + long itemToAdd = Math.min( (long) ( availablePower + 0.9 ), stored ); - if ( itemToAdd > 0 ) + if( itemToAdd > 0 ) { energy.extractAEPower( stored, Actionable.MODULATE, PowerMultiplier.CONFIG ); - if ( itemToAdd < input.getStackSize() ) + if( itemToAdd < input.getStackSize() ) { long original = input.getStackSize(); StackType split = (StackType) input.copy(); @@ -1405,10 +1379,10 @@ public class Platform input.setStackSize( itemToAdd ); split.add( cell.injectItems( input, Actionable.MODULATE, src ) ); - if ( src.isPlayer() ) + if( src.isPlayer() ) { long diff = original - split.getStackSize(); - Stats.ItemsInserted.addToPlayer( ((PlayerSource) src).player, (int) diff ); + Stats.ItemsInserted.addToPlayer( ( (PlayerSource) src ).player, (int) diff ); } return split; @@ -1416,10 +1390,10 @@ public class Platform StackType ret = cell.injectItems( input, Actionable.MODULATE, src ); - if ( src.isPlayer() ) + if( src.isPlayer() ) { long diff = ret == null ? input.getStackSize() : input.getStackSize() - ret.getStackSize(); - Stats.ItemsInserted.addToPlayer( ((PlayerSource) src).player, (int) diff ); + Stats.ItemsInserted.addToPlayer( ( (PlayerSource) src ).player, (int) diff ); } return ret; @@ -1428,111 +1402,110 @@ public class Platform return input; } - public static void postChanges(IStorageGrid gs, ItemStack removed, ItemStack added, BaseActionSource src) + public static void postChanges( IStorageGrid gs, ItemStack removed, ItemStack added, BaseActionSource src ) { IItemList itemChanges = AEApi.instance().storage().createItemList(); IItemList fluidChanges = AEApi.instance().storage().createFluidList(); - if ( removed != null ) + if( removed != null ) { IMEInventory myItems = AEApi.instance().registries().cell().getCellInventory( removed, null, StorageChannel.ITEMS ); - if ( myItems != null ) + if( myItems != null ) { - for (IAEItemStack is : myItems.getAvailableItems( itemChanges )) + for( IAEItemStack is : myItems.getAvailableItems( itemChanges ) ) is.setStackSize( -is.getStackSize() ); } IMEInventory myFluids = AEApi.instance().registries().cell().getCellInventory( removed, null, StorageChannel.FLUIDS ); - if ( myFluids != null ) + if( myFluids != null ) { - for (IAEFluidStack is : myFluids.getAvailableItems( fluidChanges )) + for( IAEFluidStack is : myFluids.getAvailableItems( fluidChanges ) ) is.setStackSize( -is.getStackSize() ); } } - if ( added != null ) + if( added != null ) { IMEInventory myItems = AEApi.instance().registries().cell().getCellInventory( added, null, StorageChannel.ITEMS ); - if ( myItems != null ) + if( myItems != null ) myItems.getAvailableItems( itemChanges ); IMEInventory myFluids = AEApi.instance().registries().cell().getCellInventory( added, null, StorageChannel.FLUIDS ); - if ( myFluids != null ) + if( myFluids != null ) myFluids.getAvailableItems( fluidChanges ); } gs.postAlterationOfStoredItems( StorageChannel.ITEMS, itemChanges, src ); } - static public > void postListChanges(IItemList before, IItemList after, IMEMonitorHandlerReceiver meMonitorPassthrough, - BaseActionSource source) + static public > void postListChanges( IItemList before, IItemList after, IMEMonitorHandlerReceiver meMonitorPassthrough, BaseActionSource source ) { LinkedList changes = new LinkedList(); - for (T is : before) + for( T is : before ) is.setStackSize( -is.getStackSize() ); - for (T is : after) + for( T is : after ) before.add( is ); - for (T is : before) + for( T is : before ) { - if ( is.getStackSize() != 0 ) + if( is.getStackSize() != 0 ) { changes.add( is ); } } - if ( !changes.isEmpty() ) + if( !changes.isEmpty() ) meMonitorPassthrough.postChange( null, changes, source ); } - public static int generateTileHash(TileEntity target) + public static int generateTileHash( TileEntity target ) { - if ( target == null ) + if( target == null ) return 0; int hash = target.hashCode(); - if ( target instanceof ITileStorageMonitorable ) + if( target instanceof ITileStorageMonitorable ) return 0; - else if ( target instanceof TileEntityChest ) + else if( target instanceof TileEntityChest ) { TileEntityChest chest = (TileEntityChest) target; chest.checkForAdjacentChests(); - if ( chest.adjacentChestZNeg != null ) + if( chest.adjacentChestZNeg != null ) hash ^= chest.adjacentChestZNeg.hashCode(); - else if ( chest.adjacentChestZPos != null ) + else if( chest.adjacentChestZPos != null ) hash ^= chest.adjacentChestZPos.hashCode(); - else if ( chest.adjacentChestXPos != null ) + else if( chest.adjacentChestXPos != null ) hash ^= chest.adjacentChestXPos.hashCode(); - else if ( chest.adjacentChestXNeg != null ) + else if( chest.adjacentChestXNeg != null ) hash ^= chest.adjacentChestXNeg.hashCode(); } - else if ( target instanceof IInventory ) + else if( target instanceof IInventory ) { - hash ^= ((IInventory) target).getSizeInventory(); + hash ^= ( (IInventory) target ).getSizeInventory(); - if ( target instanceof ISidedInventory ) + if( target instanceof ISidedInventory ) { - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) + for( ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) { int offset = 0; - int[] sides = ((ISidedInventory) target).getAccessibleSlotsFromSide( dir.ordinal() ); + int[] sides = ( (ISidedInventory) target ).getAccessibleSlotsFromSide( dir.ordinal() ); - if ( sides == null ) + if( sides == null ) return 0; - for (Integer Side : sides) + for( Integer Side : sides ) { - int c = (Side << ( offset % 8)) ^ (1 << dir.ordinal()); + int c = ( Side << ( offset % 8 ) ) ^ ( 1 << dir.ordinal() ); offset++; - hash = c + (hash << 6) + (hash << 16) - hash; + hash = c + ( hash << 6 ) + ( hash << 16 ) - hash; } } } @@ -1541,94 +1514,93 @@ public class Platform return hash; } - public static boolean securityCheck(GridNode a, GridNode b) + public static boolean securityCheck( GridNode a, GridNode b ) { - if ( a.lastSecurityKey == -1 && b.lastSecurityKey == -1 ) + if( a.lastSecurityKey == -1 && b.lastSecurityKey == -1 ) return false; - else if ( a.lastSecurityKey == b.lastSecurityKey ) + else if( a.lastSecurityKey == b.lastSecurityKey ) return false; boolean a_isSecure = isPowered( a.getGrid() ) && a.lastSecurityKey != -1; boolean b_isSecure = isPowered( b.getGrid() ) && b.lastSecurityKey != -1; - if ( AEConfig.instance.isFeatureEnabled( AEFeature.LogSecurityAudits ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.LogSecurityAudits ) ) { - AELog.info( "Audit: " + a_isSecure + " : " + b_isSecure + " @ " + a.lastSecurityKey + " vs " + b.lastSecurityKey + " & " + a.playerID + " vs " - + b.playerID ); + AELog.info( "Audit: " + a_isSecure + " : " + b_isSecure + " @ " + a.lastSecurityKey + " vs " + b.lastSecurityKey + " & " + a.playerID + " vs " + b.playerID ); } // can't do that son... - if ( a_isSecure && b_isSecure ) + if( a_isSecure && b_isSecure ) return true; - if ( !a_isSecure && b_isSecure ) + if( !a_isSecure && b_isSecure ) return checkPlayerPermissions( b.getGrid(), a.playerID ); - if ( a_isSecure && !b_isSecure ) + if( a_isSecure && !b_isSecure ) return checkPlayerPermissions( a.getGrid(), b.playerID ); return false; } - private static boolean isPowered(IGrid grid) + private static boolean isPowered( IGrid grid ) { - if ( grid == null ) + if( grid == null ) return false; IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); return eg.isNetworkPowered(); } - private static boolean checkPlayerPermissions(IGrid grid, int playerID) + private static boolean checkPlayerPermissions( IGrid grid, int playerID ) { - if ( grid == null ) + if( grid == null ) return false; ISecurityGrid gs = grid.getCache( ISecurityGrid.class ); - if ( gs == null ) + if( gs == null ) return false; - if ( !gs.isAvailable() ) + if( !gs.isAvailable() ) return false; return !gs.hasPermission( playerID, SecurityPermissions.BUILD ); } - public static boolean isDrawing(Tessellator tess) + public static boolean isDrawing( Tessellator tess ) { return false; } - public static void configurePlayer(EntityPlayer player, ForgeDirection side, TileEntity tile) + public static void configurePlayer( EntityPlayer player, ForgeDirection side, TileEntity tile ) { float pitch = 0.0f; float yaw = 0.0f; player.yOffset = 1.8f; - switch (side) + switch( side ) { - case DOWN: - pitch = 90.0f; - player.yOffset = -1.8f; - break; - case EAST: - yaw = -90.0f; - break; - case NORTH: - yaw = 180.0f; - break; - case SOUTH: - yaw = 0.0f; - break; - case UNKNOWN: - break; - case UP: - pitch = 90.0f; - break; - case WEST: - yaw = 90.0f; - break; + case DOWN: + pitch = 90.0f; + player.yOffset = -1.8f; + break; + case EAST: + yaw = -90.0f; + break; + case NORTH: + yaw = 180.0f; + break; + case SOUTH: + yaw = 0.0f; + break; + case UNKNOWN: + break; + case UP: + pitch = 90.0f; + break; + case WEST: + yaw = 90.0f; + break; } player.posX = tile.xCoord + 0.5; @@ -1639,19 +1611,19 @@ public class Platform player.rotationYaw = player.prevCameraYaw = player.cameraYaw = yaw; } - public static boolean canAccess(AENetworkProxy gridProxy, BaseActionSource src) + public static boolean canAccess( AENetworkProxy gridProxy, BaseActionSource src ) { try { - if ( src.isPlayer() ) + if( src.isPlayer() ) { - return gridProxy.getSecurity().hasPermission( ((PlayerSource) src).player, SecurityPermissions.BUILD ); + return gridProxy.getSecurity().hasPermission( ( (PlayerSource) src ).player, SecurityPermissions.BUILD ); } - else if ( src.isMachine() ) + else if( src.isMachine() ) { - IActionHost te = ((MachineSource) src).via; + IActionHost te = ( (MachineSource) src ).via; IGridNode n = te.getActionableNode(); - if ( n == null ) + if( n == null ) return false; int playerID = n.getPlayerID(); @@ -1660,31 +1632,29 @@ public class Platform else return false; } - catch (GridAccessException gae) + catch( GridAccessException gae ) { return false; } } - public static ItemStack extractItemsByRecipe(IEnergySource energySrc, BaseActionSource mySrc, IMEMonitor src, World w, IRecipe r, - ItemStack output, InventoryCrafting ci, ItemStack providedTemplate, int slot, IItemList items, Actionable realForFake, - IPartitionList filter) + public static ItemStack extractItemsByRecipe( IEnergySource energySrc, BaseActionSource mySrc, IMEMonitor src, World w, IRecipe r, ItemStack output, InventoryCrafting ci, ItemStack providedTemplate, int slot, IItemList items, Actionable realForFake, IPartitionList filter ) { - if ( energySrc.extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.9 ) + if( energySrc.extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.9 ) { - if ( providedTemplate == null ) + if( providedTemplate == null ) return null; AEItemStack ae_req = AEItemStack.create( providedTemplate ); ae_req.setStackSize( 1 ); - if ( filter == null || filter.isListed( ae_req ) ) + if( filter == null || filter.isListed( ae_req ) ) { IAEItemStack ae_ext = src.extractItems( ae_req, realForFake, mySrc ); - if ( ae_ext != null ) + if( ae_ext != null ) { ItemStack extracted = ae_ext.getItemStack(); - if ( extracted != null ) + if( extracted != null ) { energySrc.extractAEPower( 1, realForFake, PowerMultiplier.CONFIG ); return extracted; @@ -1692,27 +1662,26 @@ public class Platform } } - boolean checkFuzzy = ae_req.isOre() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate.hasTagCompound() - || providedTemplate.isItemStackDamageable(); + boolean checkFuzzy = ae_req.isOre() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate.hasTagCompound() || providedTemplate.isItemStackDamageable(); - if ( items != null && checkFuzzy ) + if( items != null && checkFuzzy ) { - for (IAEItemStack x : items) + for( IAEItemStack x : items ) { ItemStack sh = x.getItemStack(); - if ( (Platform.isSameItemType( providedTemplate, sh ) || ae_req.sameOre( x )) && !Platform.isSameItem( sh, output ) ) + if( ( Platform.isSameItemType( providedTemplate, sh ) || ae_req.sameOre( x ) ) && !Platform.isSameItem( sh, output ) ) { // Platform.isSameItemType( sh, providedTemplate ) ItemStack cp = Platform.cloneItemStack( sh ); cp.stackSize = 1; ci.setInventorySlotContents( slot, cp ); - if ( r.matches( ci, w ) && Platform.isSameItem( r.getCraftingResult( ci ), output ) ) + if( r.matches( ci, w ) && Platform.isSameItem( r.getCraftingResult( ci ), output ) ) { IAEItemStack ax = x.copy(); ax.setStackSize( 1 ); - if ( filter == null || filter.isListed( ax ) ) + if( filter == null || filter.isListed( ax ) ) { IAEItemStack ex = src.extractItems( ax, realForFake, mySrc ); - if ( ex != null ) + if( ex != null ) { energySrc.extractAEPower( 1, realForFake, PowerMultiplier.CONFIG ); return ex.getItemStack(); @@ -1723,20 +1692,40 @@ public class Platform } } } - } return null; } - public static ItemStack getContainerItem(ItemStack stackInSlot) + public static boolean isSameItemType( ItemStack ol, ItemStack op ) { - if ( stackInSlot == null ) + if( ol != null && op != null && ol.getItem() == op.getItem() ) + { + if( ol.isItemStackDamageable() ) + return true; + return ol.getItemDamage() == ol.getItemDamage(); + } + return false; + } + + public static boolean isSameItem( ItemStack left, ItemStack right ) + { + return left != null && right != null && left.isItemEqual( right ); + } + + public static ItemStack cloneItemStack( ItemStack a ) + { + return a.copy(); + } + + public static ItemStack getContainerItem( ItemStack stackInSlot ) + { + if( stackInSlot == null ) return null; Item i = stackInSlot.getItem(); - if ( i == null || !i.hasContainerItem( stackInSlot ) ) + if( i == null || !i.hasContainerItem( stackInSlot ) ) { - if ( stackInSlot.stackSize > 1 ) + if( stackInSlot.stackSize > 1 ) { stackInSlot.stackSize--; return stackInSlot; @@ -1745,58 +1734,58 @@ public class Platform } ItemStack ci = i.getContainerItem( stackInSlot.copy() ); - if ( ci != null && ci.isItemStackDamageable() && ci.getItemDamage() == ci.getMaxDamage() ) + if( ci != null && ci.isItemStackDamageable() && ci.getItemDamage() == ci.getMaxDamage() ) ci = null; return ci; } - public static void notifyBlocksOfNeighbors(World worldObj, int xCoord, int yCoord, int zCoord) + public static void notifyBlocksOfNeighbors( World worldObj, int xCoord, int yCoord, int zCoord ) { - if ( !worldObj.isRemote ) + if( !worldObj.isRemote ) TickHandler.INSTANCE.addCallable( worldObj, new BlockUpdate( worldObj, xCoord, yCoord, zCoord ) ); } - public static boolean canRepair(AEFeature type, ItemStack a, ItemStack b) + public static boolean canRepair( AEFeature type, ItemStack a, ItemStack b ) { - if ( b == null || a == null ) + if( b == null || a == null ) return false; - if ( type == AEFeature.CertusQuartzTools ) + if( type == AEFeature.CertusQuartzTools ) { final IItemDefinition certusQuartzCrystal = AEApi.instance().definitions().materials().certusQuartzCrystal(); return certusQuartzCrystal.isSameAs( b ); } - if ( type == AEFeature.NetherQuartzTools ) + if( type == AEFeature.NetherQuartzTools ) return Items.quartz == b.getItem(); return false; } - public static Object findPreferred(ItemStack[] is) + public static Object findPreferred( ItemStack[] is ) { final IParts parts = AEApi.instance().definitions().parts(); - for (ItemStack stack : is) + for( ItemStack stack : is ) { - if ( parts.cableGlass().sameAs( AEColor.Transparent, stack ) ) + if( parts.cableGlass().sameAs( AEColor.Transparent, stack ) ) { return stack; } - if ( parts.cableCovered().sameAs( AEColor.Transparent, stack ) ) + if( parts.cableCovered().sameAs( AEColor.Transparent, stack ) ) { return stack; } - if ( parts.cableSmart().sameAs( AEColor.Transparent, stack ) ) + if( parts.cableSmart().sameAs( AEColor.Transparent, stack ) ) { return stack; } - if ( parts.cableDense().sameAs( AEColor.Transparent, stack ) ) + if( parts.cableDense().sameAs( AEColor.Transparent, stack ) ) { return stack; } @@ -1805,87 +1794,79 @@ public class Platform return is; } - private static Class playerInstance; - private static Method getOrCreateChunkWatcher; - private static Method sendToAllPlayersWatchingChunk; - - public static void sendChunk(Chunk c, int verticalBits) + public static void sendChunk( Chunk c, int verticalBits ) { try { WorldServer ws = (WorldServer) c.worldObj; PlayerManager pm = ws.getPlayerManager(); - if ( getOrCreateChunkWatcher == null ) + if( getOrCreateChunkWatcher == null ) { - getOrCreateChunkWatcher = ReflectionHelper.findMethod( PlayerManager.class, pm, new String[] { "getOrCreateChunkWatcher", "func_72690_a" }, - int.class, int.class, boolean.class ); + getOrCreateChunkWatcher = ReflectionHelper.findMethod( PlayerManager.class, pm, new String[] { "getOrCreateChunkWatcher", "func_72690_a" }, int.class, int.class, boolean.class ); } - if ( getOrCreateChunkWatcher != null ) + if( getOrCreateChunkWatcher != null ) { Object playerInstance = getOrCreateChunkWatcher.invoke( pm, c.xPosition, c.zPosition, false ); - if ( playerInstance != null ) + if( playerInstance != null ) { Platform.playerInstance = playerInstance.getClass(); - if ( sendToAllPlayersWatchingChunk == null ) + if( sendToAllPlayersWatchingChunk == null ) { - sendToAllPlayersWatchingChunk = ReflectionHelper.findMethod( Platform.playerInstance, playerInstance, new String[] { - "sendToAllPlayersWatchingChunk", "func_151251_a" }, Packet.class ); + sendToAllPlayersWatchingChunk = ReflectionHelper.findMethod( Platform.playerInstance, playerInstance, new String[] { "sendToAllPlayersWatchingChunk", "func_151251_a" }, Packet.class ); } - if ( sendToAllPlayersWatchingChunk != null ) + if( sendToAllPlayersWatchingChunk != null ) sendToAllPlayersWatchingChunk.invoke( playerInstance, new S21PacketChunkData( c, false, verticalBits ) ); } } - } - catch (Throwable t) + catch( Throwable t ) { AELog.error( t ); } } - public static AxisAlignedBB getPrimaryBox(ForgeDirection side, int facadeThickness) + public static AxisAlignedBB getPrimaryBox( ForgeDirection side, int facadeThickness ) { - switch (side) + switch( side ) { - case DOWN: - return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, (facadeThickness) / 16.0, 1.0 ); - case EAST: - return AxisAlignedBB.getBoundingBox( (16.0 - facadeThickness) / 16.0, 0.0, 0.0, 1.0, 1.0, 1.0 ); - case NORTH: - return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, (facadeThickness) / 16.0 ); - case SOUTH: - return AxisAlignedBB.getBoundingBox( 0.0, 0.0, (16.0 - facadeThickness) / 16.0, 1.0, 1.0, 1.0 ); - case UP: - return AxisAlignedBB.getBoundingBox( 0.0, (16.0 - facadeThickness) / 16.0, 0.0, 1.0, 1.0, 1.0 ); - case WEST: - return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, (facadeThickness) / 16.0, 1.0, 1.0 ); - default: - break; - + case DOWN: + return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, ( facadeThickness ) / 16.0, 1.0 ); + case EAST: + return AxisAlignedBB.getBoundingBox( ( 16.0 - facadeThickness ) / 16.0, 0.0, 0.0, 1.0, 1.0, 1.0 ); + case NORTH: + return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, ( facadeThickness ) / 16.0 ); + case SOUTH: + return AxisAlignedBB.getBoundingBox( 0.0, 0.0, ( 16.0 - facadeThickness ) / 16.0, 1.0, 1.0, 1.0 ); + case UP: + return AxisAlignedBB.getBoundingBox( 0.0, ( 16.0 - facadeThickness ) / 16.0, 0.0, 1.0, 1.0, 1.0 ); + case WEST: + return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, ( facadeThickness ) / 16.0, 1.0, 1.0 ); + default: + break; } return AxisAlignedBB.getBoundingBox( 0, 0, 0, 1, 1, 1 ); } - public static float getEyeOffset(EntityPlayer player) + public static float getEyeOffset( EntityPlayer player ) { assert player.worldObj.isRemote : "Valid only on client"; - return (float) (player.posY + player.getEyeHeight() - player.getDefaultEyeHeight()); + return (float) ( player.posY + player.getEyeHeight() - player.getDefaultEyeHeight() ); } - public static void addStat(int playerID, Achievement achievement) + public static void addStat( int playerID, Achievement achievement ) { EntityPlayer p = AEApi.instance().registries().players().findPlayer( playerID ); - if ( p != null ) + if( p != null ) { p.addStat( achievement, 1 ); } } - public static boolean isRecipePrioritized(ItemStack what) + public static boolean isRecipePrioritized( ItemStack what ) { final IMaterials materials = AEApi.instance().definitions().materials(); diff --git a/src/main/java/appeng/util/ReadOnlyCollection.java b/src/main/java/appeng/util/ReadOnlyCollection.java index 396a982c4..8cdaa062e 100644 --- a/src/main/java/appeng/util/ReadOnlyCollection.java +++ b/src/main/java/appeng/util/ReadOnlyCollection.java @@ -18,17 +18,20 @@ package appeng.util; + import java.util.Collection; import java.util.Iterator; import appeng.api.util.IReadOnlyCollection; + public class ReadOnlyCollection implements IReadOnlyCollection { private final Collection c; - public ReadOnlyCollection(Collection in) { + public ReadOnlyCollection( Collection in ) + { this.c = in; } @@ -51,9 +54,8 @@ public class ReadOnlyCollection implements IReadOnlyCollection } @Override - public boolean contains(Object node) + public boolean contains( Object node ) { return this.c.contains( node ); } - } diff --git a/src/main/java/appeng/util/ReadableNumberConverter.java b/src/main/java/appeng/util/ReadableNumberConverter.java index 05df5e4ad..fc3bbabe2 100644 --- a/src/main/java/appeng/util/ReadableNumberConverter.java +++ b/src/main/java/appeng/util/ReadableNumberConverter.java @@ -58,6 +58,25 @@ public enum ReadableNumberConverter return String.format( "%s%d%s", sign, result, postFix ); } + /** + * Gets character representation of the sign of a number + * + * @param number maybe signed number + * + * @return '-' if the number is signed, else an empty character + */ + private String getSign( long number ) + { + if( number < 0 ) + { + return "-"; + } + else + { + return ""; + } + } + /** * Converts a number into a human readable form. It will not round the number, but floor it. * Will try to cut the number down 1 decimal earlier. This will limit the String size to 3 chars. @@ -92,23 +111,4 @@ public enum ReadableNumberConverter return String.format( "%s%d%s", sign, result, postFix ); } } - - /** - * Gets character representation of the sign of a number - * - * @param number maybe signed number - * - * @return '-' if the number is signed, else an empty character - */ - private String getSign( long number ) - { - if ( number < 0 ) - { - return "-"; - } - else - { - return ""; - } - } } diff --git a/src/main/java/appeng/util/SettingsFrom.java b/src/main/java/appeng/util/SettingsFrom.java index 6c76712a7..f187f9948 100644 --- a/src/main/java/appeng/util/SettingsFrom.java +++ b/src/main/java/appeng/util/SettingsFrom.java @@ -18,6 +18,7 @@ package appeng.util; + public enum SettingsFrom { // moved the item, and replaced it. diff --git a/src/main/java/appeng/util/inv/AdaptorBCPipe.java b/src/main/java/appeng/util/inv/AdaptorBCPipe.java index d2087563d..3b1576835 100644 --- a/src/main/java/appeng/util/inv/AdaptorBCPipe.java +++ b/src/main/java/appeng/util/inv/AdaptorBCPipe.java @@ -18,6 +18,7 @@ package appeng.util.inv; + import java.util.Iterator; import net.minecraft.item.ItemStack; @@ -31,6 +32,7 @@ import appeng.integration.abstraction.IBC; import appeng.util.InventoryAdaptor; import appeng.util.iterators.NullIterator; + public class AdaptorBCPipe extends InventoryAdaptor { @@ -38,11 +40,12 @@ public class AdaptorBCPipe extends InventoryAdaptor final private TileEntity i; final private ForgeDirection d; - public AdaptorBCPipe(TileEntity s, ForgeDirection dd) { + public AdaptorBCPipe( TileEntity s, ForgeDirection dd ) + { this.bc = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); - if ( this.bc != null ) + if( this.bc != null ) { - if ( this.bc.isPipe( s, dd ) ) + if( this.bc.isPipe( s, dd ) ) { this.i = s; this.d = dd; @@ -54,48 +57,48 @@ public class AdaptorBCPipe extends InventoryAdaptor } @Override - public ItemStack removeSimilarItems(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) + public ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ) { return null; } @Override - public ItemStack simulateSimilarRemove(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) + public ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ) { return null; } @Override - public ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination) + public ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) { return null; } @Override - public ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination) + public ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) { return null; } @Override - public ItemStack addItems(ItemStack toBeAdded ) + public ItemStack addItems( ItemStack toBeAdded ) { - if ( this.i == null ) + if( this.i == null ) return toBeAdded; - if ( toBeAdded == null ) + if( toBeAdded == null ) return null; - if ( toBeAdded.stackSize == 0 ) + if( toBeAdded.stackSize == 0 ) return null; - if ( this.bc.addItemsToPipe( this.i, toBeAdded, this.d ) ) + if( this.bc.addItemsToPipe( this.i, toBeAdded, this.d ) ) return null; return toBeAdded; } @Override - public ItemStack simulateAdd(ItemStack toBeSimulated ) + public ItemStack simulateAdd( ItemStack toBeSimulated ) { - if ( this.i == null ) + if( this.i == null ) return toBeSimulated; return null; } @@ -111,5 +114,4 @@ public class AdaptorBCPipe extends InventoryAdaptor { return new NullIterator(); } - } diff --git a/src/main/java/appeng/util/inv/AdaptorIInventory.java b/src/main/java/appeng/util/inv/AdaptorIInventory.java index 80cdbad4d..ad5a0a5d5 100644 --- a/src/main/java/appeng/util/inv/AdaptorIInventory.java +++ b/src/main/java/appeng/util/inv/AdaptorIInventory.java @@ -41,117 +41,26 @@ public class AdaptorIInventory extends InventoryAdaptor this.wrapperEnabled = s instanceof IInventoryWrapper; } - boolean canRemoveStackFromSlot( int x, ItemStack is ) - { - if ( this.wrapperEnabled ) - return ( ( IInventoryWrapper ) this.i ).canRemoveItemFromSlot( x, is ); - return true; - } - - @Override - public boolean containsItems() - { - int s = this.i.getSizeInventory(); - for ( int x = 0; x < s; x++ ) - { - if ( this.i.getStackInSlot( x ) != null ) - return true; - } - return false; - } - - @Override - public ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) - { - int s = this.i.getSizeInventory(); - for ( int x = 0; x < s; x++ ) - { - ItemStack is = this.i.getStackInSlot( x ); - if ( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) - { - int newAmount = amount; - if ( newAmount > is.stackSize ) - newAmount = is.stackSize; - if ( destination != null && !destination.canInsert( is ) ) - newAmount = 0; - - ItemStack rv = null; - if ( newAmount > 0 ) - { - rv = is.copy(); - rv.stackSize = newAmount; - - if ( is.stackSize == rv.stackSize ) - { - this.i.setInventorySlotContents( x, null ); - this.i.markDirty(); - } - else - { - ItemStack po = is.copy(); - po.stackSize -= rv.stackSize; - this.i.setInventorySlotContents( x, po ); - this.i.markDirty(); - } - } - - if ( rv != null ) - { - // i.markDirty(); - return rv; - } - } - } - return null; - } - - @Override - public ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) - { - int s = this.i.getSizeInventory(); - for ( int x = 0; x < s; x++ ) - { - ItemStack is = this.i.getStackInSlot( x ); - - if ( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) - { - int boundAmount = amount; - if ( boundAmount > is.stackSize ) - boundAmount = is.stackSize; - if ( destination != null && !destination.canInsert( is ) ) - boundAmount = 0; - - if ( boundAmount > 0 ) - { - ItemStack rv = is.copy(); - rv.stackSize = boundAmount; - return rv; - } - } - } - return null; - } - @Override public ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ) { int s = this.i.getSizeInventory(); ItemStack rv = null; - for ( int x = 0; x < s && amount > 0; x++ ) + for( int x = 0; x < s && amount > 0; x++ ) { ItemStack is = this.i.getStackInSlot( x ); - if ( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) + if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) { int boundAmounts = amount; - if ( boundAmounts > is.stackSize ) + if( boundAmounts > is.stackSize ) boundAmounts = is.stackSize; - if ( destination != null && !destination.canInsert( is ) ) + if( destination != null && !destination.canInsert( is ) ) boundAmounts = 0; - if ( boundAmounts > 0 ) + if( boundAmounts > 0 ) { - if ( rv == null ) + if( rv == null ) { rv = is.copy(); filter = rv; @@ -164,7 +73,7 @@ public class AdaptorIInventory extends InventoryAdaptor amount -= boundAmounts; } - if ( is.stackSize == boundAmounts ) + if( is.stackSize == boundAmounts ) { this.i.setInventorySlotContents( x, null ); this.i.markDirty(); @@ -192,20 +101,20 @@ public class AdaptorIInventory extends InventoryAdaptor int s = this.i.getSizeInventory(); ItemStack rv = null; - for ( int x = 0; x < s && amount > 0; x++ ) + for( int x = 0; x < s && amount > 0; x++ ) { ItemStack is = this.i.getStackInSlot( x ); - if ( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) + if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) { int boundAmount = amount; - if ( boundAmount > is.stackSize ) + if( boundAmount > is.stackSize ) boundAmount = is.stackSize; - if ( destination != null && !destination.canInsert( is ) ) + if( destination != null && !destination.canInsert( is ) ) boundAmount = 0; - if ( boundAmount > 0 ) + if( boundAmount > 0 ) { - if ( rv == null ) + if( rv == null ) { rv = is.copy(); rv.stackSize = boundAmount; @@ -223,6 +132,78 @@ public class AdaptorIInventory extends InventoryAdaptor return rv; } + @Override + public ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) + { + int s = this.i.getSizeInventory(); + for( int x = 0; x < s; x++ ) + { + ItemStack is = this.i.getStackInSlot( x ); + if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) + { + int newAmount = amount; + if( newAmount > is.stackSize ) + newAmount = is.stackSize; + if( destination != null && !destination.canInsert( is ) ) + newAmount = 0; + + ItemStack rv = null; + if( newAmount > 0 ) + { + rv = is.copy(); + rv.stackSize = newAmount; + + if( is.stackSize == rv.stackSize ) + { + this.i.setInventorySlotContents( x, null ); + this.i.markDirty(); + } + else + { + ItemStack po = is.copy(); + po.stackSize -= rv.stackSize; + this.i.setInventorySlotContents( x, po ); + this.i.markDirty(); + } + } + + if( rv != null ) + { + // i.markDirty(); + return rv; + } + } + } + return null; + } + + @Override + public ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) + { + int s = this.i.getSizeInventory(); + for( int x = 0; x < s; x++ ) + { + ItemStack is = this.i.getStackInSlot( x ); + + if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) + { + int boundAmount = amount; + if( boundAmount > is.stackSize ) + boundAmount = is.stackSize; + if( destination != null && !destination.canInsert( is ) ) + boundAmount = 0; + + if( boundAmount > 0 ) + { + ItemStack rv = is.copy(); + rv.stackSize = boundAmount; + return rv; + } + } + } + return null; + } + @Override public ItemStack addItems( ItemStack toBeAdded ) { @@ -235,6 +216,18 @@ public class AdaptorIInventory extends InventoryAdaptor return this.addItems( toBeSimulated, false ); } + @Override + public boolean containsItems() + { + int s = this.i.getSizeInventory(); + for( int x = 0; x < s; x++ ) + { + if( this.i.getStackInSlot( x ) != null ) + return true; + } + return false; + } + /** * Adds an {@link ItemStack} to the adapted {@link IInventory}. * @@ -243,13 +236,13 @@ public class AdaptorIInventory extends InventoryAdaptor * than the limit. * * @param itemsToAdd itemStack to add to the inventory - * @param modulate true to modulate, false for simulate + * @param modulate true to modulate, false for simulate * * @return the left itemstack, which could not be added */ private ItemStack addItems( ItemStack itemsToAdd, boolean modulate ) { - if ( itemsToAdd == null || itemsToAdd.stackSize == 0 ) + if( itemsToAdd == null || itemsToAdd.stackSize == 0 ) { return null; } @@ -259,35 +252,35 @@ public class AdaptorIInventory extends InventoryAdaptor int perOperationLimit = Math.min( this.i.getInventoryStackLimit(), stackLimit ); int inventorySize = this.i.getSizeInventory(); - for ( int slot = 0; slot < inventorySize; slot++ ) + for( int slot = 0; slot < inventorySize; slot++ ) { ItemStack next = left.copy(); next.stackSize = Math.min( perOperationLimit, next.stackSize ); - if ( this.i.isItemValidForSlot( slot, next ) ) + if( this.i.isItemValidForSlot( slot, next ) ) { ItemStack is = this.i.getStackInSlot( slot ); - if ( is == null ) + if( is == null ) { left.stackSize -= next.stackSize; - if ( modulate ) + if( modulate ) { this.i.setInventorySlotContents( slot, next ); this.i.markDirty(); } - if ( left.stackSize <= 0 ) + if( left.stackSize <= 0 ) { return null; } } - else if ( Platform.isSameItemPrecise( is, left ) && is.stackSize < perOperationLimit ) + else if( Platform.isSameItemPrecise( is, left ) && is.stackSize < perOperationLimit ) { int room = perOperationLimit - is.stackSize; int used = Math.min( left.stackSize, room ); - if ( modulate ) + if( modulate ) { is.stackSize += used; this.i.setInventorySlotContents( slot, is ); @@ -295,7 +288,7 @@ public class AdaptorIInventory extends InventoryAdaptor } left.stackSize -= used; - if ( left.stackSize <= 0 ) + if( left.stackSize <= 0 ) { return null; } @@ -306,6 +299,19 @@ public class AdaptorIInventory extends InventoryAdaptor return left; } + boolean canRemoveStackFromSlot( int x, ItemStack is ) + { + if( this.wrapperEnabled ) + return ( (IInventoryWrapper) this.i ).canRemoveItemFromSlot( x, is ); + return true; + } + + @Override + public Iterator iterator() + { + return new InvIterator(); + } + class InvIterator implements Iterator { @@ -336,13 +342,5 @@ public class AdaptorIInventory extends InventoryAdaptor { // nothing! } - } - - @Override - public Iterator iterator() - { - return new InvIterator(); - } - } diff --git a/src/main/java/appeng/util/inv/AdaptorList.java b/src/main/java/appeng/util/inv/AdaptorList.java index d0bfb5bd6..58b1f423e 100644 --- a/src/main/java/appeng/util/inv/AdaptorList.java +++ b/src/main/java/appeng/util/inv/AdaptorList.java @@ -18,6 +18,7 @@ package appeng.util.inv; + import java.util.Iterator; import java.util.List; @@ -28,96 +29,39 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.iterators.StackToSlotIterator; + public class AdaptorList extends InventoryAdaptor { private final List i; - public AdaptorList(List s) { + public AdaptorList( List s ) + { this.i = s; } @Override - public ItemStack removeSimilarItems(int how_many, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) + public ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ) { int s = this.i.size(); - for (int x = 0; x < s; x++) + for( int x = 0; x < s; x++ ) { ItemStack is = this.i.get( x ); - if ( is != null && (filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode )) ) + if( is != null && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) { - if ( how_many > is.stackSize ) - how_many = is.stackSize; - if ( destination != null && !destination.canInsert( is ) ) - how_many = 0; - - if ( how_many > 0 ) - { - ItemStack rv = is.copy(); - rv.stackSize = how_many; - is.stackSize -= how_many; - - // remove it.. - if ( is.stackSize <= 0 ) - this.i.remove( x ); - - return rv; - } - } - } - return null; - } - - @Override - public ItemStack simulateSimilarRemove(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) - { - for (ItemStack is : this.i) - { - if ( is != null && (filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode )) ) - { - if ( amount > is.stackSize ) - { + if( amount > is.stackSize ) amount = is.stackSize; - } - if ( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } - - if ( amount > 0 ) - { - ItemStack rv = is.copy(); - rv.stackSize = amount; - return rv; - } - } - } - return null; - - } - - @Override - public ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination) - { - int s = this.i.size(); - for (int x = 0; x < s; x++) - { - ItemStack is = this.i.get( x ); - if ( is != null && (filter == null || Platform.isSameItemPrecise( is, filter )) ) - { - if ( amount > is.stackSize ) - amount = is.stackSize; - if ( destination != null && !destination.canInsert( is ) ) + if( destination != null && !destination.canInsert( is ) ) amount = 0; - if ( amount > 0 ) + if( amount > 0 ) { ItemStack rv = is.copy(); rv.stackSize = amount; is.stackSize -= amount; // remove it.. - if ( is.stackSize <= 0 ) + if( is.stackSize <= 0 ) this.i.remove( x ); return rv; @@ -128,22 +72,22 @@ public class AdaptorList extends InventoryAdaptor } @Override - public ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination) + public ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ) { - for (ItemStack is : this.i) + for( ItemStack is : this.i ) { - if ( is != null && (filter == null || Platform.isSameItemPrecise( is, filter )) ) + if( is != null && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) { - if ( amount > is.stackSize ) + if( amount > is.stackSize ) { amount = is.stackSize; } - if ( destination != null && !destination.canInsert( is ) ) + if( destination != null && !destination.canInsert( is ) ) { amount = 0; } - if ( amount > 0 ) + if( amount > 0 ) { ItemStack rv = is.copy(); rv.stackSize = amount; @@ -152,22 +96,79 @@ public class AdaptorList extends InventoryAdaptor } } return null; - } @Override - public ItemStack addItems(ItemStack toBeAdded ) + public ItemStack removeSimilarItems( int how_many, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) { - if ( toBeAdded == null ) + int s = this.i.size(); + for( int x = 0; x < s; x++ ) + { + ItemStack is = this.i.get( x ); + if( is != null && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) + { + if( how_many > is.stackSize ) + how_many = is.stackSize; + if( destination != null && !destination.canInsert( is ) ) + how_many = 0; + + if( how_many > 0 ) + { + ItemStack rv = is.copy(); + rv.stackSize = how_many; + is.stackSize -= how_many; + + // remove it.. + if( is.stackSize <= 0 ) + this.i.remove( x ); + + return rv; + } + } + } + return null; + } + + @Override + public ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) + { + for( ItemStack is : this.i ) + { + if( is != null && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) + { + if( amount > is.stackSize ) + { + amount = is.stackSize; + } + if( destination != null && !destination.canInsert( is ) ) + { + amount = 0; + } + + if( amount > 0 ) + { + ItemStack rv = is.copy(); + rv.stackSize = amount; + return rv; + } + } + } + return null; + } + + @Override + public ItemStack addItems( ItemStack toBeAdded ) + { + if( toBeAdded == null ) return null; - if ( toBeAdded.stackSize == 0 ) + if( toBeAdded.stackSize == 0 ) return null; ItemStack left = toBeAdded.copy(); - for (ItemStack is : this.i) + for( ItemStack is : this.i ) { - if ( Platform.isSameItem( is, left ) ) + if( Platform.isSameItem( is, left ) ) { is.stackSize += left.stackSize; return null; @@ -179,7 +180,7 @@ public class AdaptorList extends InventoryAdaptor } @Override - public ItemStack simulateAdd(ItemStack toBeSimulated ) + public ItemStack simulateAdd( ItemStack toBeSimulated ) { return null; } @@ -187,9 +188,9 @@ public class AdaptorList extends InventoryAdaptor @Override public boolean containsItems() { - for (ItemStack is : this.i) + for( ItemStack is : this.i ) { - if ( is != null ) + if( is != null ) { return true; } @@ -202,5 +203,4 @@ public class AdaptorList extends InventoryAdaptor { return new StackToSlotIterator( this.i.iterator() ); } - } diff --git a/src/main/java/appeng/util/inv/AdaptorPlayerHand.java b/src/main/java/appeng/util/inv/AdaptorPlayerHand.java index 0f9d4fc58..2722aa03b 100644 --- a/src/main/java/appeng/util/inv/AdaptorPlayerHand.java +++ b/src/main/java/appeng/util/inv/AdaptorPlayerHand.java @@ -1,4 +1,3 @@ - /* * This file is part of Applied Energistics 2. * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. @@ -44,57 +43,19 @@ public class AdaptorPlayerHand extends InventoryAdaptor this.p = _p; } - @Override - public ItemStack removeSimilarItems( int how_many, ItemStack Filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) - { - ItemStack hand = this.p.inventory.getItemStack(); - if ( hand == null ) - return null; - - if ( Filter == null || Platform.isSameItemFuzzy( Filter, hand, fuzzyMode ) ) - { - ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > how_many ? how_many : hand.stackSize; - hand.stackSize -= how_many; - if ( hand.stackSize <= 0 ) - this.p.inventory.setItemStack( null ); - return result; - } - - return null; - } - - @Override - public ItemStack simulateSimilarRemove( int amount, ItemStack Filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) - { - - ItemStack hand = this.p.inventory.getItemStack(); - if ( hand == null ) - return null; - - if ( Filter == null || Platform.isSameItemFuzzy( Filter, hand, fuzzyMode ) ) - { - ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - return result; - } - - return null; - } - @Override public ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ) { ItemStack hand = this.p.inventory.getItemStack(); - if ( hand == null ) + if( hand == null ) return null; - if ( filter == null || Platform.isSameItemPrecise( filter, hand ) ) + if( filter == null || Platform.isSameItemPrecise( filter, hand ) ) { ItemStack result = hand.copy(); result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; hand.stackSize -= amount; - if ( hand.stackSize <= 0 ) + if( hand.stackSize <= 0 ) this.p.inventory.setItemStack( null ); return result; } @@ -107,10 +68,48 @@ public class AdaptorPlayerHand extends InventoryAdaptor { ItemStack hand = this.p.inventory.getItemStack(); - if ( hand == null ) + if( hand == null ) return null; - if ( filter == null || Platform.isSameItemPrecise( filter, hand ) ) + if( filter == null || Platform.isSameItemPrecise( filter, hand ) ) + { + ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + return result; + } + + return null; + } + + @Override + public ItemStack removeSimilarItems( int how_many, ItemStack Filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) + { + ItemStack hand = this.p.inventory.getItemStack(); + if( hand == null ) + return null; + + if( Filter == null || Platform.isSameItemFuzzy( Filter, hand, fuzzyMode ) ) + { + ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > how_many ? how_many : hand.stackSize; + hand.stackSize -= how_many; + if( hand.stackSize <= 0 ) + this.p.inventory.setItemStack( null ); + return result; + } + + return null; + } + + @Override + public ItemStack simulateSimilarRemove( int amount, ItemStack Filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) + { + + ItemStack hand = this.p.inventory.getItemStack(); + if( hand == null ) + return null; + + if( Filter == null || Platform.isSameItemFuzzy( Filter, hand, fuzzyMode ) ) { ItemStack result = hand.copy(); result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; @@ -124,23 +123,23 @@ public class AdaptorPlayerHand extends InventoryAdaptor public ItemStack addItems( ItemStack toBeAdded ) { - if ( toBeAdded == null ) + if( toBeAdded == null ) return null; - if ( toBeAdded.stackSize == 0 ) + if( toBeAdded.stackSize == 0 ) return null; - if ( this.p == null ) + if( this.p == null ) return toBeAdded; - if ( this.p.inventory == null ) + if( this.p.inventory == null ) return toBeAdded; ItemStack hand = this.p.inventory.getItemStack(); - if ( hand != null && !Platform.isSameItemPrecise( toBeAdded, hand ) ) + if( hand != null && !Platform.isSameItemPrecise( toBeAdded, hand ) ) return toBeAdded; int original = 0; ItemStack newHand = null; - if ( hand == null ) + if( hand == null ) newHand = toBeAdded.copy(); else { @@ -149,7 +148,7 @@ public class AdaptorPlayerHand extends InventoryAdaptor newHand.stackSize += toBeAdded.stackSize; } - if ( newHand.stackSize > newHand.getMaxStackSize() ) + if( newHand.stackSize > newHand.getMaxStackSize() ) { newHand.stackSize = newHand.getMaxStackSize(); ItemStack B = toBeAdded.copy(); @@ -166,15 +165,15 @@ public class AdaptorPlayerHand extends InventoryAdaptor public ItemStack simulateAdd( ItemStack toBeSimulated ) { ItemStack hand = this.p.inventory.getItemStack(); - if ( toBeSimulated == null ) + if( toBeSimulated == null ) return null; - if ( hand != null && !Platform.isSameItem( toBeSimulated, hand ) ) + if( hand != null && !Platform.isSameItem( toBeSimulated, hand ) ) return toBeSimulated; int original = 0; ItemStack newHand = null; - if ( hand == null ) + if( hand == null ) newHand = toBeSimulated.copy(); else { @@ -183,7 +182,7 @@ public class AdaptorPlayerHand extends InventoryAdaptor newHand.stackSize += toBeSimulated.stackSize; } - if ( newHand.stackSize > newHand.getMaxStackSize() ) + if( newHand.stackSize > newHand.getMaxStackSize() ) { newHand.stackSize = newHand.getMaxStackSize(); ItemStack B = toBeSimulated.copy(); diff --git a/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java b/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java index b2fc00194..2117b13f9 100644 --- a/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java +++ b/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java @@ -18,25 +18,26 @@ package appeng.util.inv; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class AdaptorPlayerInventory implements IInventory { private final IInventory src; - private final int min=0; - private final int size=36; + private final int min = 0; + private final int size = 36; - public AdaptorPlayerInventory(IInventory playerInv, boolean swap) + public AdaptorPlayerInventory( IInventory playerInv, boolean swap ) { - if ( swap ) - this.src = new WrapperChainedInventory( new WrapperInventoryRange( playerInv, 9, this.size -9, false ), new WrapperInventoryRange( playerInv, 0, 9, false ) ); + if( swap ) + this.src = new WrapperChainedInventory( new WrapperInventoryRange( playerInv, 9, this.size - 9, false ), new WrapperInventoryRange( playerInv, 0, 9, false ) ); else this.src = playerInv; - } @Override @@ -46,25 +47,25 @@ public class AdaptorPlayerInventory implements IInventory } @Override - public ItemStack getStackInSlot(int var1) + public ItemStack getStackInSlot( int var1 ) { return this.src.getStackInSlot( var1 + this.min ); } @Override - public ItemStack decrStackSize(int var1, int var2) + public ItemStack decrStackSize( int var1, int var2 ) { return this.src.decrStackSize( this.min + var1, var2 ); } @Override - public ItemStack getStackInSlotOnClosing(int var1) + public ItemStack getStackInSlotOnClosing( int var1 ) { return this.src.getStackInSlotOnClosing( this.min + var1 ); } @Override - public void setInventorySlotContents(int var1, ItemStack var2) + public void setInventorySlotContents( int var1, ItemStack var2 ) { this.src.setInventorySlotContents( var1 + this.min, var2 ); } @@ -75,6 +76,12 @@ public class AdaptorPlayerInventory implements IInventory return this.src.getInventoryName(); } + @Override + public boolean hasCustomInventoryName() + { + return false; + } + @Override public int getInventoryStackLimit() { @@ -88,7 +95,7 @@ public class AdaptorPlayerInventory implements IInventory } @Override - public boolean isUseableByPlayer(EntityPlayer var1) + public boolean isUseableByPlayer( EntityPlayer var1 ) { return this.src.isUseableByPlayer( var1 ); } @@ -106,15 +113,8 @@ public class AdaptorPlayerInventory implements IInventory } @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { return this.src.isItemValidForSlot( i, itemstack ); } - } diff --git a/src/main/java/appeng/util/inv/IInventoryDestination.java b/src/main/java/appeng/util/inv/IInventoryDestination.java index 4ce01550c..61a3cf8b9 100644 --- a/src/main/java/appeng/util/inv/IInventoryDestination.java +++ b/src/main/java/appeng/util/inv/IInventoryDestination.java @@ -18,11 +18,12 @@ package appeng.util.inv; + import net.minecraft.item.ItemStack; + public interface IInventoryDestination { boolean canInsert( ItemStack stack ); - } diff --git a/src/main/java/appeng/util/inv/IInventoryWrapper.java b/src/main/java/appeng/util/inv/IInventoryWrapper.java index 09db54b9f..eedab2a70 100644 --- a/src/main/java/appeng/util/inv/IInventoryWrapper.java +++ b/src/main/java/appeng/util/inv/IInventoryWrapper.java @@ -18,11 +18,12 @@ package appeng.util.inv; + import net.minecraft.item.ItemStack; + public interface IInventoryWrapper { - boolean canRemoveItemFromSlot(int x, ItemStack is); - + boolean canRemoveItemFromSlot( int x, ItemStack is ); } diff --git a/src/main/java/appeng/util/inv/IMEAdaptor.java b/src/main/java/appeng/util/inv/IMEAdaptor.java index a202ec51f..155e036f5 100644 --- a/src/main/java/appeng/util/inv/IMEAdaptor.java +++ b/src/main/java/appeng/util/inv/IMEAdaptor.java @@ -18,12 +18,13 @@ package appeng.util.inv; + import java.util.Iterator; -import com.google.common.collect.ImmutableList; - import net.minecraft.item.ItemStack; +import com.google.common.collect.ImmutableList; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -34,6 +35,7 @@ import appeng.api.storage.data.IItemList; import appeng.util.InventoryAdaptor; import appeng.util.item.AEItemStack; + public class IMEAdaptor extends InventoryAdaptor { @@ -41,52 +43,37 @@ public class IMEAdaptor extends InventoryAdaptor final BaseActionSource src; int maxSlots = 0; - public IMEAdaptor(IMEInventory input, BaseActionSource src) { + public IMEAdaptor( IMEInventory input, BaseActionSource src ) + { this.target = input; this.src = src; } - IItemList getList() - { - return this.target.getAvailableItems( AEApi.instance().storage().createItemList() ); - } - @Override public Iterator iterator() { return new IMEAdaptorIterator( this, this.getList() ); } - public ItemStack doRemoveItemsFuzzy(int how_many, ItemStack Filter, IInventoryDestination destination, Actionable type, FuzzyMode fuzzyMode) + IItemList getList() { - IAEItemStack reqFilter = AEItemStack.create( Filter ); - if ( reqFilter == null ) - return null; - - IAEItemStack out = null; - - for (IAEItemStack req : ImmutableList.copyOf( this.getList().findFuzzy( reqFilter, fuzzyMode ) )) - { - if ( req != null ) - { - req.setStackSize( how_many ); - out = this.target.extractItems( req, type, this.src ); - if ( out != null ) - return out.getItemStack(); - } - } - - return null; + return this.target.getAvailableItems( AEApi.instance().storage().createItemList() ); } - public ItemStack doRemoveItems(int how_many, ItemStack Filter, IInventoryDestination destination, Actionable type) + @Override + public ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ) + { + return this.doRemoveItems( amount, filter, destination, Actionable.MODULATE ); + } + + public ItemStack doRemoveItems( int how_many, ItemStack Filter, IInventoryDestination destination, Actionable type ) { IAEItemStack req = null; - if ( Filter == null ) + if( Filter == null ) { IItemList list = this.getList(); - if ( !list.isEmpty() ) + if( !list.isEmpty() ) req = list.getFirstItem(); } else @@ -94,67 +81,83 @@ public class IMEAdaptor extends InventoryAdaptor IAEItemStack out = null; - if ( req != null ) + if( req != null ) { req.setStackSize( how_many ); out = this.target.extractItems( req, type, this.src ); } - if ( out != null ) + if( out != null ) return out.getItemStack(); return null; } @Override - public ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination) - { - return this.doRemoveItems( amount, filter, destination, Actionable.MODULATE ); - } - - @Override - public ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination) + public ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ) { return this.doRemoveItems( amount, filter, destination, Actionable.SIMULATE ); } @Override - public ItemStack removeSimilarItems(int how_many, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) + public ItemStack removeSimilarItems( int how_many, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) { - if ( filter == null ) + if( filter == null ) return this.doRemoveItems( how_many, null, destination, Actionable.MODULATE ); return this.doRemoveItemsFuzzy( how_many, filter, destination, Actionable.MODULATE, fuzzyMode ); } - @Override - public ItemStack simulateSimilarRemove(int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination) + public ItemStack doRemoveItemsFuzzy( int how_many, ItemStack Filter, IInventoryDestination destination, Actionable type, FuzzyMode fuzzyMode ) { - if ( filter == null ) + IAEItemStack reqFilter = AEItemStack.create( Filter ); + if( reqFilter == null ) + return null; + + IAEItemStack out = null; + + for( IAEItemStack req : ImmutableList.copyOf( this.getList().findFuzzy( reqFilter, fuzzyMode ) ) ) + { + if( req != null ) + { + req.setStackSize( how_many ); + out = this.target.extractItems( req, type, this.src ); + if( out != null ) + return out.getItemStack(); + } + } + + return null; + } + + @Override + public ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ) + { + if( filter == null ) return this.doRemoveItems( amount, null, destination, Actionable.SIMULATE ); return this.doRemoveItemsFuzzy( amount, filter, destination, Actionable.SIMULATE, fuzzyMode ); } @Override - public ItemStack addItems(ItemStack toBeAdded ) + public ItemStack addItems( ItemStack toBeAdded ) { IAEItemStack in = AEItemStack.create( toBeAdded ); - if ( in != null ) + if( in != null ) { IAEItemStack out = this.target.injectItems( in, Actionable.MODULATE, this.src ); - if ( out != null ) + if( out != null ) return out.getItemStack(); } return null; } @Override - public ItemStack simulateAdd(ItemStack toBeSimulated ) + public ItemStack simulateAdd( ItemStack toBeSimulated ) { IAEItemStack in = AEItemStack.create( toBeSimulated ); - if ( in != null ) + if( in != null ) { IAEItemStack out = this.target.injectItems( in, Actionable.SIMULATE, this.src ); - if ( out != null ) + if( out != null ) return out.getItemStack(); } return null; @@ -165,5 +168,4 @@ public class IMEAdaptor extends InventoryAdaptor { return !this.getList().isEmpty(); } - } diff --git a/src/main/java/appeng/util/inv/IMEAdaptorIterator.java b/src/main/java/appeng/util/inv/IMEAdaptorIterator.java index 215b0ee3d..959e3a69a 100644 --- a/src/main/java/appeng/util/inv/IMEAdaptorIterator.java +++ b/src/main/java/appeng/util/inv/IMEAdaptorIterator.java @@ -18,23 +18,25 @@ package appeng.util.inv; + import java.util.Iterator; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; + public class IMEAdaptorIterator implements Iterator { final Iterator stack; final ItemSlot slot = new ItemSlot(); + final IMEAdaptor parent; + final int containerSize; int offset = 0; boolean hasNext; - final IMEAdaptor parent; - final int containerSize; - - public IMEAdaptorIterator(IMEAdaptor parent, IItemList availableItems) { + public IMEAdaptorIterator( IMEAdaptor parent, IItemList availableItems ) + { this.stack = availableItems.iterator(); this.containerSize = parent.maxSlots; this.parent = parent; @@ -52,12 +54,12 @@ public class IMEAdaptorIterator implements Iterator { this.slot.slot = this.offset; this.offset++; - this.slot.isExtractable=true; + this.slot.isExtractable = true; - if ( this.parent.maxSlots < this.offset ) + if( this.parent.maxSlots < this.offset ) this.parent.maxSlots = this.offset; - if ( this.hasNext ) + if( this.hasNext ) { IAEItemStack item = this.stack.next(); this.slot.setAEItemStack( item ); diff --git a/src/main/java/appeng/util/inv/IMEInventoryDestination.java b/src/main/java/appeng/util/inv/IMEInventoryDestination.java index e1273820e..681e02ad5 100644 --- a/src/main/java/appeng/util/inv/IMEInventoryDestination.java +++ b/src/main/java/appeng/util/inv/IMEInventoryDestination.java @@ -18,6 +18,7 @@ package appeng.util.inv; + import net.minecraft.item.ItemStack; import appeng.api.config.Actionable; @@ -25,27 +26,28 @@ import appeng.api.storage.IMEInventory; import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; + public class IMEInventoryDestination implements IInventoryDestination { final IMEInventory me; - public IMEInventoryDestination(IMEInventory o) { + public IMEInventoryDestination( IMEInventory o ) + { this.me = o; } @Override - public boolean canInsert(ItemStack stack) + public boolean canInsert( ItemStack stack ) { - if ( stack == null ) + if( stack == null ) return false; IAEItemStack failed = this.me.injectItems( AEItemStack.create( stack ), Actionable.SIMULATE, null ); - if ( failed == null ) + if( failed == null ) return true; return failed.getStackSize() != stack.stackSize; } - } diff --git a/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java b/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java index 7ef223ec6..c17841fbf 100644 --- a/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java +++ b/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java @@ -18,6 +18,7 @@ package appeng.util.inv; + import java.util.Collection; import java.util.Iterator; @@ -25,19 +26,21 @@ import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; + public class ItemListIgnoreCrafting implements IItemList { final IItemList target; - public ItemListIgnoreCrafting(IItemList cla) { + public ItemListIgnoreCrafting( IItemList cla ) + { this.target = cla; } @Override - public void add(T option) + public void add( T option ) { - if ( option != null && option.isCraftable() ) + if( option != null && option.isCraftable() ) { option = (T) option.copy(); option.setCraftable( false ); @@ -47,19 +50,13 @@ public class ItemListIgnoreCrafting implements IItemList } @Override - public void addCrafting(T option) - { - // nothing. - } - - @Override - public T findPrecise(T i) + public T findPrecise( T i ) { return this.target.findPrecise( i ); } @Override - public Collection findFuzzy(T input, FuzzyMode fuzzy) + public Collection findFuzzy( T input, FuzzyMode fuzzy ) { return this.target.findFuzzy( input, fuzzy ); } @@ -71,13 +68,19 @@ public class ItemListIgnoreCrafting implements IItemList } @Override - public void addStorage(T option) + public void addStorage( T option ) { this.target.addStorage( option ); } @Override - public void addRequestable(T option) + public void addCrafting( T option ) + { + // nothing. + } + + @Override + public void addRequestable( T option ) { this.target.addRequestable( option ); } diff --git a/src/main/java/appeng/util/inv/ItemSlot.java b/src/main/java/appeng/util/inv/ItemSlot.java index b2dc7e359..5ee62c4d2 100644 --- a/src/main/java/appeng/util/inv/ItemSlot.java +++ b/src/main/java/appeng/util/inv/ItemSlot.java @@ -18,42 +18,41 @@ package appeng.util.inv; + import net.minecraft.item.ItemStack; import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; + public class ItemSlot { public int slot; - + public boolean isExtractable; // one or the other.. private IAEItemStack aeItemStack; private ItemStack itemStack; - public boolean isExtractable; + public ItemStack getItemStack() + { + return this.itemStack == null ? ( this.aeItemStack == null ? null : ( this.itemStack = this.aeItemStack.getItemStack() ) ) : this.itemStack; + } - public void setItemStack(ItemStack is) + public void setItemStack( ItemStack is ) { this.aeItemStack = null; this.itemStack = is; } - public void setAEItemStack(IAEItemStack is) + public IAEItemStack getAEItemStack() + { + return this.aeItemStack == null ? ( this.itemStack == null ? null : ( this.aeItemStack = AEItemStack.create( this.itemStack ) ) ) : this.aeItemStack; + } + + public void setAEItemStack( IAEItemStack is ) { this.aeItemStack = is; this.itemStack = null; } - - public ItemStack getItemStack() - { - return this.itemStack == null ? (this.aeItemStack == null ? null : (this.itemStack = this.aeItemStack.getItemStack())) : this.itemStack; - } - - public IAEItemStack getAEItemStack() - { - return this.aeItemStack == null ? (this.itemStack == null ? null : (this.aeItemStack = AEItemStack.create( this.itemStack ))) : this.aeItemStack; - } - } diff --git a/src/main/java/appeng/util/inv/WrapperBCPipe.java b/src/main/java/appeng/util/inv/WrapperBCPipe.java index 722edb2be..0b399044a 100644 --- a/src/main/java/appeng/util/inv/WrapperBCPipe.java +++ b/src/main/java/appeng/util/inv/WrapperBCPipe.java @@ -18,6 +18,7 @@ package appeng.util.inv; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -28,6 +29,7 @@ import appeng.core.AppEng; import appeng.integration.IntegrationType; import appeng.integration.abstraction.IBC; + public class WrapperBCPipe implements IInventory { @@ -35,7 +37,8 @@ public class WrapperBCPipe implements IInventory final private TileEntity ad; final private ForgeDirection dir; - public WrapperBCPipe(TileEntity te, ForgeDirection d) { + public WrapperBCPipe( TileEntity te, ForgeDirection d ) + { this.bc = (IBC) AppEng.instance.getIntegration( IntegrationType.BC ); this.ad = te; this.dir = d; @@ -48,25 +51,25 @@ public class WrapperBCPipe implements IInventory } @Override - public ItemStack getStackInSlot(int i) + public ItemStack getStackInSlot( int i ) { return null; } @Override - public ItemStack decrStackSize(int i, int j) + public ItemStack decrStackSize( int i, int j ) { return null; } @Override - public ItemStack getStackInSlotOnClosing(int i) + public ItemStack getStackInSlotOnClosing( int i ) { return null; } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public void setInventorySlotContents( int i, ItemStack itemstack ) { this.bc.addItemsToPipe( this.ad, itemstack, this.dir ); } @@ -83,18 +86,6 @@ public class WrapperBCPipe implements IInventory return false; } - @Override - public void closeInventory() - { - - } - - @Override - public void openInventory() - { - - } - @Override public int getInventoryStackLimit() { @@ -108,15 +99,26 @@ public class WrapperBCPipe implements IInventory } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) + public boolean isUseableByPlayer( EntityPlayer entityplayer ) { return false; } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public void openInventory() + { + + } + + @Override + public void closeInventory() + { + + } + + @Override + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { return this.bc.canAddItemsToPipe( this.ad, itemstack, this.dir ); } - } diff --git a/src/main/java/appeng/util/inv/WrapperChainedInventory.java b/src/main/java/appeng/util/inv/WrapperChainedInventory.java index ad3eab001..eb9b20d1b 100644 --- a/src/main/java/appeng/util/inv/WrapperChainedInventory.java +++ b/src/main/java/appeng/util/inv/WrapperChainedInventory.java @@ -18,50 +18,34 @@ package appeng.util.inv; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import com.google.common.collect.ImmutableList; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +import com.google.common.collect.ImmutableList; + + public class WrapperChainedInventory implements IInventory { - static class InvOffset - { - - int offset; - int size; - IInventory i; - } - int fullSize = 0; - private List l; private HashMap offsets; - public WrapperChainedInventory(IInventory... inventories) { - this.setInventory( inventories ); - } - - public WrapperChainedInventory(List inventories) { - this.setInventory( inventories ); - } - - public void cycleOrder() + public WrapperChainedInventory( IInventory... inventories ) { - if ( this.l.size() > 1 ) - { - List newOrder = new ArrayList( this.l.size() ); - newOrder.add( this.l.get( this.l.size() - 1 ) ); - for (int x = 0; x < this.l.size() - 1; x++) - newOrder.add( this.l.get( x ) ); - this.setInventory( newOrder ); - } + this.setInventory( inventories ); + } + + public void setInventory( IInventory... a ) + { + this.l = ImmutableList.copyOf( a ); + this.calculateSizes(); } public void calculateSizes() @@ -69,14 +53,14 @@ public class WrapperChainedInventory implements IInventory this.offsets = new HashMap(); int offset = 0; - for (IInventory in : this.l) + for( IInventory in : this.l ) { InvOffset io = new InvOffset(); io.offset = offset; io.size = in.getSizeInventory(); io.i = in; - for (int y = 0; y < io.size; y++) + for( int y = 0; y < io.size; y++ ) { this.offsets.put( y + io.offset, io ); } @@ -87,32 +71,43 @@ public class WrapperChainedInventory implements IInventory this.fullSize = offset; } - public void setInventory(IInventory... a) + public WrapperChainedInventory( List inventories ) { - this.l = ImmutableList.copyOf( a ); - this.calculateSizes(); + this.setInventory( inventories ); } - public void setInventory(List a) + public void setInventory( List a ) { this.l = a; this.calculateSizes(); } - public IInventory getInv(int idx) + public void cycleOrder() + { + if( this.l.size() > 1 ) + { + List newOrder = new ArrayList( this.l.size() ); + newOrder.add( this.l.get( this.l.size() - 1 ) ); + for( int x = 0; x < this.l.size() - 1; x++ ) + newOrder.add( this.l.get( x ) ); + this.setInventory( newOrder ); + } + } + + public IInventory getInv( int idx ) { InvOffset io = this.offsets.get( idx ); - if ( io != null ) + if( io != null ) { return io.i; } return null; } - public int getInvSlot(int idx) + public int getInvSlot( int idx ) { InvOffset io = this.offsets.get( idx ); - if ( io != null ) + if( io != null ) { return idx - io.offset; } @@ -126,10 +121,10 @@ public class WrapperChainedInventory implements IInventory } @Override - public ItemStack getStackInSlot(int idx) + public ItemStack getStackInSlot( int idx ) { InvOffset io = this.offsets.get( idx ); - if ( io != null ) + if( io != null ) { return io.i.getStackInSlot( idx - io.offset ); } @@ -137,10 +132,10 @@ public class WrapperChainedInventory implements IInventory } @Override - public ItemStack decrStackSize(int idx, int var2) + public ItemStack decrStackSize( int idx, int var2 ) { InvOffset io = this.offsets.get( idx ); - if ( io != null ) + if( io != null ) { return io.i.decrStackSize( idx - io.offset, var2 ); } @@ -148,10 +143,10 @@ public class WrapperChainedInventory implements IInventory } @Override - public ItemStack getStackInSlotOnClosing(int idx) + public ItemStack getStackInSlotOnClosing( int idx ) { InvOffset io = this.offsets.get( idx ); - if ( io != null ) + if( io != null ) { return io.i.getStackInSlotOnClosing( idx - io.offset ); } @@ -159,10 +154,10 @@ public class WrapperChainedInventory implements IInventory } @Override - public void setInventorySlotContents(int idx, ItemStack var2) + public void setInventorySlotContents( int idx, ItemStack var2 ) { InvOffset io = this.offsets.get( idx ); - if ( io != null ) + if( io != null ) { io.i.setInventorySlotContents( idx - io.offset, var2 ); } @@ -174,12 +169,18 @@ public class WrapperChainedInventory implements IInventory return "ChainedInv"; } + @Override + public boolean hasCustomInventoryName() + { + return false; + } + @Override public int getInventoryStackLimit() { int smallest = 64; - for (IInventory i : this.l) + for( IInventory i : this.l ) smallest = Math.min( smallest, i.getInventoryStackLimit() ); return smallest; @@ -188,14 +189,14 @@ public class WrapperChainedInventory implements IInventory @Override public void markDirty() { - for (IInventory i : this.l) + for( IInventory i : this.l ) { i.markDirty(); } } @Override - public boolean isUseableByPlayer(EntityPlayer var1) + public boolean isUseableByPlayer( EntityPlayer var1 ) { return false; } @@ -211,20 +212,21 @@ public class WrapperChainedInventory implements IInventory } @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public boolean isItemValidForSlot(int idx, ItemStack itemstack) + public boolean isItemValidForSlot( int idx, ItemStack itemstack ) { InvOffset io = this.offsets.get( idx ); - if ( io != null ) + if( io != null ) { return io.i.isItemValidForSlot( idx - io.offset, itemstack ); } return false; } + static class InvOffset + { + + int offset; + int size; + IInventory i; + } } diff --git a/src/main/java/appeng/util/inv/WrapperInvSlot.java b/src/main/java/appeng/util/inv/WrapperInvSlot.java index 2c85cdcf0..3bd379780 100644 --- a/src/main/java/appeng/util/inv/WrapperInvSlot.java +++ b/src/main/java/appeng/util/inv/WrapperInvSlot.java @@ -18,20 +18,40 @@ package appeng.util.inv; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class WrapperInvSlot { + private final IInventory inv; + + public WrapperInvSlot( IInventory inv ) + { + this.inv = inv; + } + + public IInventory getWrapper( int slot ) + { + return new InternalInterfaceWrapper( this.inv, slot ); + } + + protected boolean isItemValid( ItemStack itemstack ) + { + return true; + } + class InternalInterfaceWrapper implements IInventory { private final IInventory inv; private final int slot; - public InternalInterfaceWrapper(IInventory target, int slot) { + public InternalInterfaceWrapper( IInventory target, int slot ) + { this.inv = target; this.slot = slot; } @@ -43,25 +63,25 @@ public class WrapperInvSlot } @Override - public ItemStack getStackInSlot(int i) + public ItemStack getStackInSlot( int i ) { return this.inv.getStackInSlot( this.slot ); } @Override - public ItemStack decrStackSize(int i, int num) + public ItemStack decrStackSize( int i, int num ) { return this.inv.decrStackSize( this.slot, num ); } @Override - public ItemStack getStackInSlotOnClosing(int i) + public ItemStack getStackInSlotOnClosing( int i ) { return this.inv.getStackInSlotOnClosing( this.slot ); } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public void setInventorySlotContents( int i, ItemStack itemstack ) { this.inv.setInventorySlotContents( this.slot, itemstack ); } @@ -91,7 +111,7 @@ public class WrapperInvSlot } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) + public boolean isUseableByPlayer( EntityPlayer entityplayer ) { return this.inv.isUseableByPlayer( entityplayer ); } @@ -109,26 +129,9 @@ public class WrapperInvSlot } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { return WrapperInvSlot.this.isItemValid( itemstack ) && this.inv.isItemValidForSlot( this.slot, itemstack ); } } - - private final IInventory inv; - - public WrapperInvSlot(IInventory inv) { - this.inv = inv; - } - - public IInventory getWrapper(int slot) - { - return new InternalInterfaceWrapper( this.inv, slot ); - } - - protected boolean isItemValid(ItemStack itemstack) - { - return true; - } - } diff --git a/src/main/java/appeng/util/inv/WrapperInventoryRange.java b/src/main/java/appeng/util/inv/WrapperInventoryRange.java index 7f05f7ab9..bb3520b69 100644 --- a/src/main/java/appeng/util/inv/WrapperInventoryRange.java +++ b/src/main/java/appeng/util/inv/WrapperInventoryRange.java @@ -18,25 +18,47 @@ package appeng.util.inv; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class WrapperInventoryRange implements IInventory { private final IInventory src; - int[] slots; protected boolean ignoreValidItems = false; + int[] slots; - public static String concatLines(int[] s, String separator) + public WrapperInventoryRange( IInventory a, int[] s, boolean ignoreValid ) { - if ( s.length > 0 ) + this.src = a; + this.slots = s; + + if( this.slots == null ) + this.slots = new int[0]; + + this.ignoreValidItems = ignoreValid; + } + + public WrapperInventoryRange( IInventory a, int _min, int _size, boolean ignoreValid ) + { + this.src = a; + this.slots = new int[_size]; + for( int x = 0; x < _size; x++ ) + this.slots[x] = _min + x; + this.ignoreValidItems = ignoreValid; + } + + public static String concatLines( int[] s, String separator ) + { + if( s.length > 0 ) { StringBuilder sb = new StringBuilder(); - for (int value : s) + for( int value : s ) { - if ( sb.length() > 0 ) + if( sb.length() > 0 ) { sb.append( separator ); } @@ -47,24 +69,6 @@ public class WrapperInventoryRange implements IInventory return ""; } - public WrapperInventoryRange(IInventory a, int[] s, boolean ignoreValid) { - this.src = a; - this.slots = s; - - if ( this.slots == null ) - this.slots = new int[0]; - - this.ignoreValidItems = ignoreValid; - } - - public WrapperInventoryRange(IInventory a, int _min, int _size, boolean ignoreValid) { - this.src = a; - this.slots = new int[_size]; - for (int x = 0; x < _size; x++) - this.slots[x] = _min + x; - this.ignoreValidItems = ignoreValid; - } - @Override public int getSizeInventory() { @@ -72,25 +76,25 @@ public class WrapperInventoryRange implements IInventory } @Override - public ItemStack getStackInSlot(int var1) + public ItemStack getStackInSlot( int var1 ) { return this.src.getStackInSlot( this.slots[var1] ); } @Override - public ItemStack decrStackSize(int var1, int var2) + public ItemStack decrStackSize( int var1, int var2 ) { return this.src.decrStackSize( this.slots[var1], var2 ); } @Override - public ItemStack getStackInSlotOnClosing(int var1) + public ItemStack getStackInSlotOnClosing( int var1 ) { return this.src.getStackInSlotOnClosing( this.slots[var1] ); } @Override - public void setInventorySlotContents(int var1, ItemStack var2) + public void setInventorySlotContents( int var1, ItemStack var2 ) { this.src.setInventorySlotContents( this.slots[var1], var2 ); } @@ -101,6 +105,12 @@ public class WrapperInventoryRange implements IInventory return this.src.getInventoryName(); } + @Override + public boolean hasCustomInventoryName() + { + return false; + } + @Override public int getInventoryStackLimit() { @@ -114,7 +124,7 @@ public class WrapperInventoryRange implements IInventory } @Override - public boolean isUseableByPlayer(EntityPlayer var1) + public boolean isUseableByPlayer( EntityPlayer var1 ) { return this.src.isUseableByPlayer( var1 ); } @@ -132,18 +142,11 @@ public class WrapperInventoryRange implements IInventory } @Override - public boolean hasCustomInventoryName() + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { - return false; - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) - { - if ( this.ignoreValidItems ) + if( this.ignoreValidItems ) return true; return this.src.isItemValidForSlot( this.slots[i], itemstack ); } - } diff --git a/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java b/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java index a9d82e9cc..e55a3d7c2 100644 --- a/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java +++ b/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java @@ -18,50 +18,52 @@ package appeng.util.inv; + import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; + public class WrapperMCISidedInventory extends WrapperInventoryRange implements IInventoryWrapper { - private final ForgeDirection dir; final ISidedInventory side; + private final ForgeDirection dir; - public WrapperMCISidedInventory(ISidedInventory a, ForgeDirection d) { + public WrapperMCISidedInventory( ISidedInventory a, ForgeDirection d ) + { super( a, a.getAccessibleSlotsFromSide( d.ordinal() ), false ); this.side = a; this.dir = d; } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public ItemStack decrStackSize( int var1, int var2 ) + { + if( this.canRemoveItemFromSlot( var1, this.getStackInSlot( var1 ) ) ) + return super.decrStackSize( var1, var2 ); + return null; + } + + @Override + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { - if ( this.ignoreValidItems ) + if( this.ignoreValidItems ) return true; - if ( this.side.isItemValidForSlot( this.slots[i], itemstack ) ) + if( this.side.isItemValidForSlot( this.slots[i], itemstack ) ) return this.side.canInsertItem( this.slots[i], itemstack, this.dir.ordinal() ); return false; } @Override - public boolean canRemoveItemFromSlot(int i, ItemStack is) + public boolean canRemoveItemFromSlot( int i, ItemStack is ) { - if ( is == null ) + if( is == null ) return false; return this.side.canExtractItem( this.slots[i], is, this.dir.ordinal() ); } - - @Override - public ItemStack decrStackSize(int var1, int var2) - { - if ( this.canRemoveItemFromSlot( var1, this.getStackInSlot( var1 ) ) ) - return super.decrStackSize( var1, var2 ); - return null; - } - } diff --git a/src/main/java/appeng/util/inv/WrapperTEPipe.java b/src/main/java/appeng/util/inv/WrapperTEPipe.java index 57fc4d4e3..5436eca71 100644 --- a/src/main/java/appeng/util/inv/WrapperTEPipe.java +++ b/src/main/java/appeng/util/inv/WrapperTEPipe.java @@ -18,19 +18,22 @@ package appeng.util.inv; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; + public class WrapperTEPipe implements IInventory { final TileEntity ad; final ForgeDirection dir; - public WrapperTEPipe(TileEntity te, ForgeDirection d) { + public WrapperTEPipe( TileEntity te, ForgeDirection d ) + { this.ad = te; this.dir = d; } @@ -42,25 +45,25 @@ public class WrapperTEPipe implements IInventory } @Override - public ItemStack getStackInSlot(int i) + public ItemStack getStackInSlot( int i ) { return null; } @Override - public ItemStack decrStackSize(int i, int j) + public ItemStack decrStackSize( int i, int j ) { return null; } @Override - public ItemStack getStackInSlotOnClosing(int i) + public ItemStack getStackInSlotOnClosing( int i ) { return null; } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) + public void setInventorySlotContents( int i, ItemStack itemstack ) { // ITE.addItemsToPipe( ad, itemstack, dir ); } @@ -90,7 +93,7 @@ public class WrapperTEPipe implements IInventory } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) + public boolean isUseableByPlayer( EntityPlayer entityplayer ) { return false; } @@ -108,9 +111,8 @@ public class WrapperTEPipe implements IInventory } @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) + public boolean isItemValidForSlot( int i, ItemStack itemstack ) { return false; } - } diff --git a/src/main/java/appeng/util/item/AEFluidStack.java b/src/main/java/appeng/util/item/AEFluidStack.java index b0b12796f..1beee7ece 100644 --- a/src/main/java/appeng/util/item/AEFluidStack.java +++ b/src/main/java/appeng/util/item/AEFluidStack.java @@ -18,6 +18,7 @@ package appeng.util.item; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; @@ -38,6 +39,7 @@ import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAETagCompound; import appeng.util.Platform; + public final class AEFluidStack extends AEStack implements IAEFluidStack, Comparable { @@ -45,33 +47,8 @@ public final class AEFluidStack extends AEStack implements IAEFlu Fluid fluid; private IAETagCompound tagCompound; - @Override - public String toString() + private AEFluidStack( AEFluidStack is ) { - return this.getFluidStack().toString(); - } - - @Override - public IAETagCompound getTagCompound() - { - return this.tagCompound; - } - - @Override - public void add(IAEFluidStack option) - { - if ( option == null ) - return; - - // if ( priority < ((AEFluidStack) option).priority ) - // priority = ((AEFluidStack) option).priority; - - this.incStackSize( option.getStackSize() ); - this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); - this.setCraftable( this.isCraftable() || option.isCraftable() ); - } - - private AEFluidStack(AEFluidStack is) { this.fluid = is.fluid; this.stackSize = is.stackSize; @@ -83,85 +60,109 @@ public final class AEFluidStack extends AEStack implements IAEFlu this.myHash = is.myHash; } - private AEFluidStack( FluidStack is ) { - if ( is == null ) + private AEFluidStack( FluidStack is ) + { + if( is == null ) throw new RuntimeException( "Invalid Itemstack." ); this.fluid = is.getFluid(); - if ( this.fluid == null ) + if( this.fluid == null ) throw new RuntimeException( "Fluid is null." ); this.stackSize = is.amount; this.setCraftable( false ); this.setCountRequestable( 0 ); - this.myHash = this.fluid.hashCode() ^ (this.tagCompound == null ? 0 : System.identityHashCode( this.tagCompound )); + this.myHash = this.fluid.hashCode() ^ ( this.tagCompound == null ? 0 : System.identityHashCode( this.tagCompound ) ); } - public static AEFluidStack create(Object a) + public static IAEFluidStack loadFluidStackFromNBT( NBTTagCompound i ) { - if ( a == null ) + ItemStack itemstack = ItemStack.loadItemStackFromNBT( i ); + if( itemstack == null ) return null; - if ( a instanceof AEFluidStack ) - ((AEFluidStack) a).copy(); - if ( a instanceof FluidStack ) + AEFluidStack fluid = AEFluidStack.create( itemstack ); + // fluid.priority = i.getInteger( "Priority" ); + fluid.stackSize = i.getLong( "Cnt" ); + fluid.setCountRequestable( i.getLong( "Req" ) ); + fluid.setCraftable( i.getBoolean( "Craft" ) ); + return fluid; + } + + public static AEFluidStack create( Object a ) + { + if( a == null ) + return null; + if( a instanceof AEFluidStack ) + ( (AEFluidStack) a ).copy(); + if( a instanceof FluidStack ) return new AEFluidStack( (FluidStack) a ); return null; } - @Override - public boolean equals(Object ia) + public static IAEFluidStack loadFluidStackFromPacket( ByteBuf data ) throws IOException { - if ( ia instanceof AEFluidStack ) + byte mask = data.readByte(); + // byte PriorityType = (byte) (mask & 0x03); + byte StackType = (byte) ( ( mask & 0x0C ) >> 2 ); + byte CountReqType = (byte) ( ( mask & 0x30 ) >> 4 ); + boolean isCraftable = ( mask & 0x40 ) > 0; + boolean hasTagCompound = ( mask & 0x80 ) > 0; + + // don't send this... + NBTTagCompound d = new NBTTagCompound(); + + byte len2 = data.readByte(); + byte[] name = new byte[len2]; + data.readBytes( name, 0, len2 ); + + d.setString( "FluidName", new String( name, "UTF-8" ) ); + d.setByte( "Count", (byte) 0 ); + + if( hasTagCompound ) { - return ((AEFluidStack) ia).fluid == this.fluid && this.tagCompound == ((AEFluidStack) ia).tagCompound; + int len = data.readInt(); + + byte[] bd = new byte[len]; + data.readBytes( bd ); + + DataInputStream di = new DataInputStream( new ByteArrayInputStream( bd ) ); + d.setTag( "tag", CompressedStreamTools.read( di ) ); } - else if ( ia instanceof FluidStack ) - { - FluidStack is = (FluidStack) ia; - if ( is.fluidID == this.fluid.getID() ) - { - NBTTagCompound ta = (NBTTagCompound) this.tagCompound; - NBTTagCompound tb = is.tag; - if ( ta == tb ) - return true; + // long priority = getPacketValue( PriorityType, data ); + long stackSize = getPacketValue( StackType, data ); + long countRequestable = getPacketValue( CountReqType, data ); - if ( (ta == null && tb == null) || (ta != null && ta.hasNoTags() && tb == null) || (tb != null && tb.hasNoTags() && ta == null) - || (ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags()) ) - return true; + FluidStack fluidStack = FluidStack.loadFluidStackFromNBT( d ); + if( fluidStack == null ) + return null; - if ( (ta == null && tb != null) || (ta != null && tb == null) ) - return false; - - if ( AESharedNBT.isShared( tb ) ) - return ta == tb; - - return Platform.NBTEqualityTest( ta, tb ); - } - } - return false; + AEFluidStack fluid = AEFluidStack.create( fluidStack ); + // fluid.priority = (int) priority; + fluid.stackSize = stackSize; + fluid.setCountRequestable( countRequestable ); + fluid.setCraftable( isCraftable ); + return fluid; } @Override - public FluidStack getFluidStack() + public void add( IAEFluidStack option ) { - FluidStack is = new FluidStack( this.fluid, (int) Math.min( Integer.MAX_VALUE, this.stackSize ) ); - if ( this.tagCompound != null ) - is.tag = this.tagCompound.getNBTTagCompoundCopy(); + if( option == null ) + return; - return is; + // if ( priority < ((AEFluidStack) option).priority ) + // priority = ((AEFluidStack) option).priority; + + this.incStackSize( option.getStackSize() ); + this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); + this.setCraftable( this.isCraftable() || option.isCraftable() ); } @Override - public IAEFluidStack copy() - { - return new AEFluidStack( this ); - } - - @Override - public void writeToNBT(NBTTagCompound i) + public void writeToNBT( NBTTagCompound i ) { /* * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the memory department. @@ -196,123 +197,35 @@ public final class AEFluidStack extends AEStack implements IAEFlu /* * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = (byte) (this.isCraftable() ? * 1 : 0); else - */i.setBoolean( "Craft", this.isCraftable() ); + */ + i.setBoolean( "Craft", this.isCraftable() ); - if ( this.tagCompound != null ) + if( this.tagCompound != null ) i.setTag( "tag", (NBTTagCompound) this.tagCompound ); else i.removeTag( "tag" ); - - } - - public static IAEFluidStack loadFluidStackFromNBT(NBTTagCompound i) - { - ItemStack itemstack = ItemStack.loadItemStackFromNBT( i ); - if ( itemstack == null ) - return null; - AEFluidStack fluid = AEFluidStack.create( itemstack ); - // fluid.priority = i.getInteger( "Priority" ); - fluid.stackSize = i.getLong( "Cnt" ); - fluid.setCountRequestable( i.getLong( "Req" ) ); - fluid.setCraftable( i.getBoolean( "Craft" ) ); - return fluid; } @Override - public boolean hasTagCompound() + public boolean fuzzyComparison( Object st, FuzzyMode mode ) { - return this.tagCompound != null; - } - - @Override - public int hashCode() - { - return this.myHash; - } - - @Override - public int compareTo(AEFluidStack b) - { - int diff = this.hashCode() - b.hashCode(); - return diff > 0 ? 1 : (diff < 0 ? -1 : 0); - } - - @Override - void writeIdentity(ByteBuf i) throws IOException - { - byte[] name = this.fluid.getName().getBytes( "UTF-8" ); - i.writeByte( (byte) name.length ); - i.writeBytes( name ); - } - - @Override - void readNBT(ByteBuf i) throws IOException - { - if ( this.hasTagCompound() ) + if( st instanceof FluidStack ) { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - DataOutputStream data = new DataOutputStream( bytes ); - - CompressedStreamTools.write( (NBTTagCompound) this.tagCompound, data ); - - byte[] tagBytes = bytes.toByteArray(); - int size = tagBytes.length; - - i.writeInt( size ); - i.writeBytes( tagBytes ); - } - } - - public static IAEFluidStack loadFluidStackFromPacket(ByteBuf data) throws IOException - { - byte mask = data.readByte(); - // byte PriorityType = (byte) (mask & 0x03); - byte StackType = (byte) ((mask & 0x0C) >> 2); - byte CountReqType = (byte) ((mask & 0x30) >> 4); - boolean isCraftable = (mask & 0x40) > 0; - boolean hasTagCompound = (mask & 0x80) > 0; - - // don't send this... - NBTTagCompound d = new NBTTagCompound(); - - byte len2 = data.readByte(); - byte[] name = new byte[len2]; - data.readBytes( name, 0, len2 ); - - d.setString( "FluidName", new String( name, "UTF-8" ) ); - d.setByte( "Count", (byte) 0 ); - - if ( hasTagCompound ) - { - int len = data.readInt(); - - byte[] bd = new byte[len]; - data.readBytes( bd ); - - DataInputStream di = new DataInputStream( new ByteArrayInputStream( bd ) ); - d.setTag( "tag", CompressedStreamTools.read( di ) ); + return ( (FluidStack) st ).getFluid() == this.fluid; } - // long priority = getPacketValue( PriorityType, data ); - long stackSize = getPacketValue( StackType, data ); - long countRequestable = getPacketValue( CountReqType, data ); + if( st instanceof IAEFluidStack ) + { + return ( (IAEFluidStack) st ).getFluid() == this.fluid; + } - FluidStack fluidStack = FluidStack.loadFluidStackFromNBT( d ); - if ( fluidStack == null ) - return null; - - AEFluidStack fluid = AEFluidStack.create( fluidStack ); - // fluid.priority = (int) priority; - fluid.stackSize = stackSize; - fluid.setCountRequestable( countRequestable ); - fluid.setCraftable( isCraftable ); - return fluid; + return false; } @Override - public Fluid getFluid() + public IAEFluidStack copy() { - return this.fluid; + return new AEFluidStack( this ); } @Override @@ -324,19 +237,9 @@ public final class AEFluidStack extends AEStack implements IAEFlu } @Override - public boolean fuzzyComparison(Object st, FuzzyMode mode) + public IAETagCompound getTagCompound() { - if ( st instanceof FluidStack ) - { - return ((FluidStack) st).getFluid() == this.fluid; - } - - if ( st instanceof IAEFluidStack ) - { - return ((IAEFluidStack) st).getFluid() == this.fluid; - } - - return false; + return this.tagCompound; } @Override @@ -357,4 +260,103 @@ public final class AEFluidStack extends AEStack implements IAEFlu return StorageChannel.FLUIDS; } + @Override + public int compareTo( AEFluidStack b ) + { + int diff = this.hashCode() - b.hashCode(); + return diff > 0 ? 1 : ( diff < 0 ? -1 : 0 ); + } + + @Override + public int hashCode() + { + return this.myHash; + } + + @Override + public boolean equals( Object ia ) + { + if( ia instanceof AEFluidStack ) + { + return ( (AEFluidStack) ia ).fluid == this.fluid && this.tagCompound == ( (AEFluidStack) ia ).tagCompound; + } + else if( ia instanceof FluidStack ) + { + FluidStack is = (FluidStack) ia; + + if( is.fluidID == this.fluid.getID() ) + { + NBTTagCompound ta = (NBTTagCompound) this.tagCompound; + NBTTagCompound tb = is.tag; + if( ta == tb ) + return true; + + if( ( ta == null && tb == null ) || ( ta != null && ta.hasNoTags() && tb == null ) || ( tb != null && tb.hasNoTags() && ta == null ) || ( ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags() ) ) + return true; + + if( ( ta == null && tb != null ) || ( ta != null && tb == null ) ) + return false; + + if( AESharedNBT.isShared( tb ) ) + return ta == tb; + + return Platform.NBTEqualityTest( ta, tb ); + } + } + return false; + } + + @Override + public String toString() + { + return this.getFluidStack().toString(); + } @Override + public boolean hasTagCompound() + { + return this.tagCompound != null; + } + + @Override + public FluidStack getFluidStack() + { + FluidStack is = new FluidStack( this.fluid, (int) Math.min( Integer.MAX_VALUE, this.stackSize ) ); + if( this.tagCompound != null ) + is.tag = this.tagCompound.getNBTTagCompoundCopy(); + + return is; + } + + @Override + public Fluid getFluid() + { + return this.fluid; + } + + + + @Override + void writeIdentity( ByteBuf i ) throws IOException + { + byte[] name = this.fluid.getName().getBytes( "UTF-8" ); + i.writeByte( (byte) name.length ); + i.writeBytes( name ); + } + + @Override + void readNBT( ByteBuf i ) throws IOException + { + if( this.hasTagCompound() ) + { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream data = new DataOutputStream( bytes ); + + CompressedStreamTools.write( (NBTTagCompound) this.tagCompound, data ); + + byte[] tagBytes = bytes.toByteArray(); + int size = tagBytes.length; + + i.writeInt( size ); + i.writeBytes( tagBytes ); + } + } } diff --git a/src/main/java/appeng/util/item/AEItemDef.java b/src/main/java/appeng/util/item/AEItemDef.java index bf10167cb..a643ad742 100644 --- a/src/main/java/appeng/util/item/AEItemDef.java +++ b/src/main/java/appeng/util/item/AEItemDef.java @@ -18,6 +18,7 @@ package appeng.util.item; + import java.util.List; import net.minecraft.init.Items; @@ -30,37 +31,30 @@ import cpw.mods.fml.relauncher.SideOnly; import appeng.util.Platform; + public class AEItemDef { - public int myHash; - - public int def; - - public final int itemID; - public final Item item; - public int damageValue; - - public int displayDamage; - public int maxDamage; - - public AESharedNBT tagCompound; - - @SideOnly(Side.CLIENT) - public String displayName; - - @SideOnly(Side.CLIENT) - public List tooltip; - - @SideOnly(Side.CLIENT) - public UniqueIdentifier uniqueID; - - public OreReference isOre; - static final AESharedNBT LOW_TAG = new AESharedNBT( Integer.MIN_VALUE ); static final AESharedNBT HIGH_TAG = new AESharedNBT( Integer.MAX_VALUE ); + public final int itemID; + public final Item item; + public int myHash; + public int def; + public int damageValue; + public int displayDamage; + public int maxDamage; + public AESharedNBT tagCompound; + @SideOnly( Side.CLIENT ) + public String displayName; + @SideOnly( Side.CLIENT ) + public List tooltip; + @SideOnly( Side.CLIENT ) + public UniqueIdentifier uniqueID; + public OreReference isOre; - public AEItemDef(Item it) { + public AEItemDef( Item it ) + { this.item = it; this.itemID = Item.getIdFromItem( it ); } @@ -78,32 +72,27 @@ public class AEItemDef } @Override - public boolean equals(Object obj) + public boolean equals( Object obj ) { - if ( obj == null ) + if( obj == null ) return false; - if ( this.getClass() != obj.getClass() ) + if( this.getClass() != obj.getClass() ) return false; AEItemDef other = (AEItemDef) obj; return other.damageValue == this.damageValue && other.item == this.item && this.tagCompound == other.tagCompound; } - public int getDamageValueHack(ItemStack is) - { - return Items.blaze_rod.getDamage( is ); - } - - public boolean isItem(ItemStack otherStack) + public boolean isItem( ItemStack otherStack ) { // hackery! int dmg = this.getDamageValueHack( otherStack ); - if ( this.item == otherStack.getItem() && dmg == this.damageValue ) + if( this.item == otherStack.getItem() && dmg == this.damageValue ) { - if ( (this.tagCompound != null) == otherStack.hasTagCompound() ) + if( ( this.tagCompound != null ) == otherStack.hasTagCompound() ) return true; - if ( this.tagCompound != null && otherStack.hasTagCompound() ) + if( this.tagCompound != null && otherStack.hasTagCompound() ) return Platform.NBTEqualityTest( this.tagCompound, otherStack.getTagCompound() ); return true; @@ -111,9 +100,14 @@ public class AEItemDef return false; } + public int getDamageValueHack( ItemStack is ) + { + return Items.blaze_rod.getDamage( is ); + } + public void reHash() { this.def = this.itemID << Platform.DEF_OFFSET | this.damageValue; - this.myHash = this.def ^ (this.tagCompound == null ? 0 : System.identityHashCode( this.tagCompound )); + this.myHash = this.def ^ ( this.tagCompound == null ? 0 : System.identityHashCode( this.tagCompound ) ); } } diff --git a/src/main/java/appeng/util/item/AEItemStack.java b/src/main/java/appeng/util/item/AEItemStack.java index aa894c219..47c55b328 100644 --- a/src/main/java/appeng/util/item/AEItemStack.java +++ b/src/main/java/appeng/util/item/AEItemStack.java @@ -396,51 +396,6 @@ public final class AEItemStack extends AEStack implements IAEItemS return StorageChannel.ITEMS; } - @Override - public int hashCode() - { - return this.def.myHash; - } - - @Override - public boolean equals( Object ia ) - { - if( ia instanceof AEItemStack ) - { - return ( (AEItemStack) ia ).def.equals( this.def );// && def.tagCompound == ((AEItemStack) ia).def.tagCompound; - } - else if( ia instanceof ItemStack ) - { - ItemStack is = (ItemStack) ia; - - if( is.getItem() == this.def.item && is.getItemDamage() == this.def.damageValue ) - { - NBTTagCompound ta = this.def.tagCompound; - NBTTagCompound tb = is.getTagCompound(); - if( ta == tb ) - return true; - - if( ( ta == null && tb == null ) || ( ta != null && ta.hasNoTags() && tb == null ) || ( tb != null && tb.hasNoTags() && ta == null ) || ( ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags() ) ) - return true; - - if( ( ta == null && tb != null ) || ( ta != null && tb == null ) ) - return false; - - if( AESharedNBT.isShared( tb ) ) - return ta == tb; - - return Platform.NBTEqualityTest( ta, tb ); - } - } - return false; - } - - @Override - public String toString() - { - return this.getItemStack().toString(); - } - @Override public ItemStack getItemStack() { @@ -487,6 +442,51 @@ public final class AEItemStack extends AEStack implements IAEItemS return this.def.isItem( otherStack ); } + @Override + public int hashCode() + { + return this.def.myHash; + } + + @Override + public boolean equals( Object ia ) + { + if( ia instanceof AEItemStack ) + { + return ( (AEItemStack) ia ).def.equals( this.def );// && def.tagCompound == ((AEItemStack) ia).def.tagCompound; + } + else if( ia instanceof ItemStack ) + { + ItemStack is = (ItemStack) ia; + + if( is.getItem() == this.def.item && is.getItemDamage() == this.def.damageValue ) + { + NBTTagCompound ta = this.def.tagCompound; + NBTTagCompound tb = is.getTagCompound(); + if( ta == tb ) + return true; + + if( ( ta == null && tb == null ) || ( ta != null && ta.hasNoTags() && tb == null ) || ( tb != null && tb.hasNoTags() && ta == null ) || ( ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags() ) ) + return true; + + if( ( ta == null && tb != null ) || ( ta != null && tb == null ) ) + return false; + + if( AESharedNBT.isShared( tb ) ) + return ta == tb; + + return Platform.NBTEqualityTest( ta, tb ); + } + } + return false; + } + + @Override + public String toString() + { + return this.getItemStack().toString(); + } + @Override public int compareTo( AEItemStack b ) { @@ -553,37 +553,6 @@ public final class AEItemStack extends AEStack implements IAEItemS return uniqueIdentifier.modId == null ? "** Null" : uniqueIdentifier.modId; } - @Override - void writeIdentity( ByteBuf i ) throws IOException - { - i.writeShort( Item.itemRegistry.getIDForObject( this.def.item ) ); - i.writeShort( this.getItemDamage() ); - } - - @Override - void readNBT( ByteBuf i ) throws IOException - { - if( this.hasTagCompound() ) - { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - DataOutputStream data = new DataOutputStream( bytes ); - - CompressedStreamTools.write( (NBTTagCompound) this.getTagCompound(), data ); - - byte[] tagBytes = bytes.toByteArray(); - int size = tagBytes.length; - - i.writeInt( size ); - i.writeBytes( tagBytes ); - } - } - - @Override - public boolean hasTagCompound() - { - return this.def.tagCompound != null; - } - public IAEItemStack getLow( FuzzyMode fuzzy, boolean ignoreMeta ) { AEItemStack bottom = new AEItemStack( this ); @@ -666,4 +635,35 @@ public final class AEItemStack extends AEStack implements IAEItemS { return this.def.isOre != null; } + + @Override + void writeIdentity( ByteBuf i ) throws IOException + { + i.writeShort( Item.itemRegistry.getIDForObject( this.def.item ) ); + i.writeShort( this.getItemDamage() ); + } + + @Override + void readNBT( ByteBuf i ) throws IOException + { + if( this.hasTagCompound() ) + { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream data = new DataOutputStream( bytes ); + + CompressedStreamTools.write( (NBTTagCompound) this.getTagCompound(), data ); + + byte[] tagBytes = bytes.toByteArray(); + int size = tagBytes.length; + + i.writeInt( size ); + i.writeBytes( tagBytes ); + } + } + + @Override + public boolean hasTagCompound() + { + return this.def.tagCompound != null; + } } diff --git a/src/main/java/appeng/util/item/AESharedNBT.java b/src/main/java/appeng/util/item/AESharedNBT.java index 2907da282..94eb519a0 100644 --- a/src/main/java/appeng/util/item/AESharedNBT.java +++ b/src/main/java/appeng/util/item/AESharedNBT.java @@ -18,6 +18,7 @@ package appeng.util.item; + import java.lang.ref.WeakReference; import java.util.WeakHashMap; @@ -30,54 +31,100 @@ import appeng.api.features.IItemComparison; import appeng.api.storage.data.IAETagCompound; import appeng.util.Platform; + /* * this is used for the shared NBT Cache. */ public class AESharedNBT extends NBTTagCompound implements IAETagCompound { + /* + * Shared Tag Compound Cache. + */ + private static final WeakHashMap> SHARED_TAG_COMPOUND = new WeakHashMap>(); private final Item item; private final int meta; - private int hash; public SharedSearchObject sso; + private int hash; private IItemComparison comp; - public int getHash() + private AESharedNBT( Item itemID, int damageValue ) { - return this.hash; - } - - @Override - public IItemComparison getSpecialComparison() - { - return this.comp; - } - - private AESharedNBT(Item itemID, int damageValue) { super(); this.item = itemID; this.meta = damageValue; } - public AESharedNBT(int fakeValue) { + public AESharedNBT( int fakeValue ) + { super(); this.item = null; this.meta = 0; this.hash = fakeValue; } - @Override - public NBTTagCompound getNBTTagCompoundCopy() + /* + * Debug purposes. + */ + public static int sharedTagLoad() { - return (NBTTagCompound) this.copy(); + return SHARED_TAG_COMPOUND.size(); } - public static AESharedNBT createFromCompound(Item itemID, int damageValue, NBTTagCompound c) + /* + * Returns an NBT Compound that is used for accelerating comparisons. + */ + synchronized public static NBTTagCompound getSharedTagCompound( NBTTagCompound tagCompound, ItemStack s ) + { + if( tagCompound.hasNoTags() ) + return null; + + Item item = s.getItem(); + int meta = -1; + if( s.getItem() != null && s.isItemStackDamageable() && s.getHasSubtypes() ) + meta = s.getItemDamage(); + + if( isShared( tagCompound ) ) + return tagCompound; + + SharedSearchObject sso = new SharedSearchObject( item, meta, tagCompound ); + + WeakReference c = SHARED_TAG_COMPOUND.get( sso ); + if( c != null ) + { + SharedSearchObject cg = c.get(); + if( cg != null ) + return cg.shared; // I don't think I really need to check this + // as its already certain to exist.. + } + + AESharedNBT clone = AESharedNBT.createFromCompound( item, meta, tagCompound ); + sso.compound = (NBTTagCompound) sso.compound.copy(); // prevent + // modification + // of data based + // on original + // item. + sso.shared = clone; + clone.sso = sso; + + SHARED_TAG_COMPOUND.put( sso, new WeakReference( sso ) ); + return clone; + } + + /* + * returns true if the compound is part of the shared compound system ( and can thus be compared directly ). + */ + public static boolean isShared( NBTTagCompound ta ) + { + return ta instanceof AESharedNBT; + } + + public static AESharedNBT createFromCompound( Item itemID, int damageValue, NBTTagCompound c ) { AESharedNBT x = new AESharedNBT( itemID, damageValue ); // c.getTags() - for (Object o : c.func_150296_c()) + for( Object o : c.func_150296_c() ) { String name = (String) o; x.setTag( name, c.getTag( name ).copy() ); @@ -92,25 +139,42 @@ public class AESharedNBT extends NBTTagCompound implements IAETagCompound return x; } - @Override - public boolean equals(Object par1Obj) + public int getHash() { - if ( par1Obj instanceof AESharedNBT ) + return this.hash; + } + + @Override + public NBTTagCompound getNBTTagCompoundCopy() + { + return (NBTTagCompound) this.copy(); + } + + @Override + public IItemComparison getSpecialComparison() + { + return this.comp; + } + + @Override + public boolean equals( Object par1Obj ) + { + if( par1Obj instanceof AESharedNBT ) return this == par1Obj; return super.equals( par1Obj ); } - public boolean matches(Item item, int meta, int orderlessHash) + public boolean matches( Item item, int meta, int orderlessHash ) { return item == this.item && this.meta == meta && this.hash == orderlessHash; } - public boolean comparePreciseWithRegistry(AESharedNBT tagCompound) + public boolean comparePreciseWithRegistry( AESharedNBT tagCompound ) { - if ( this == tagCompound ) + if( this == tagCompound ) return true; - if ( this.comp != null && tagCompound.comp != null ) + if( this.comp != null && tagCompound.comp != null ) { return this.comp.sameAsPrecise( tagCompound.comp ); } @@ -118,83 +182,21 @@ public class AESharedNBT extends NBTTagCompound implements IAETagCompound return false; } - public boolean compareFuzzyWithRegistry(AESharedNBT tagCompound) + public boolean compareFuzzyWithRegistry( AESharedNBT tagCompound ) { - if ( this == tagCompound ) + if( this == tagCompound ) return true; - if ( tagCompound == null ) + if( tagCompound == null ) return false; - if ( this.comp == tagCompound.comp ) + if( this.comp == tagCompound.comp ) return true; - if ( this.comp != null ) + if( this.comp != null ) { return this.comp.sameAsFuzzy( tagCompound.comp ); } return false; } - - /* - * Shared Tag Compound Cache. - */ - private static final WeakHashMap> SHARED_TAG_COMPOUND = new WeakHashMap>(); - - /* - * Debug purposes. - */ - public static int sharedTagLoad() - { - return SHARED_TAG_COMPOUND.size(); - } - - /* - * returns true if the compound is part of the shared compound system ( and can thus be compared directly ). - */ - public static boolean isShared(NBTTagCompound ta) - { - return ta instanceof AESharedNBT; - } - - /* - * Returns an NBT Compound that is used for accelerating comparisons. - */ - synchronized public static NBTTagCompound getSharedTagCompound(NBTTagCompound tagCompound, ItemStack s) - { - if ( tagCompound.hasNoTags() ) - return null; - - Item item = s.getItem(); - int meta = -1; - if ( s.getItem() != null && s.isItemStackDamageable() && s.getHasSubtypes() ) - meta = s.getItemDamage(); - - if ( isShared( tagCompound ) ) - return tagCompound; - - SharedSearchObject sso = new SharedSearchObject( item, meta, tagCompound ); - - WeakReference c = SHARED_TAG_COMPOUND.get( sso ); - if ( c != null ) - { - SharedSearchObject cg = c.get(); - if ( cg != null ) - return cg.shared; // I don't think I really need to check this - // as its already certain to exist.. - } - - AESharedNBT clone = AESharedNBT.createFromCompound( item, meta, tagCompound ); - sso.compound = (NBTTagCompound) sso.compound.copy(); // prevent - // modification - // of data based - // on original - // item. - sso.shared = clone; - clone.sso = sso; - - SHARED_TAG_COMPOUND.put( sso, new WeakReference( sso ) ); - return clone; - } - } diff --git a/src/main/java/appeng/util/item/AEStack.java b/src/main/java/appeng/util/item/AEStack.java index f631a8144..f79a00780 100644 --- a/src/main/java/appeng/util/item/AEStack.java +++ b/src/main/java/appeng/util/item/AEStack.java @@ -18,12 +18,14 @@ package appeng.util.item; + import java.io.IOException; import io.netty.buffer.ByteBuf; import appeng.api.storage.data.IAEStack; + public abstract class AEStack implements IAEStack { @@ -31,10 +33,67 @@ public abstract class AEStack implements IAEStack 0 || this.isCraftable; + if( type == 0 ) + { + long l = tag.readByte(); + l -= Byte.MIN_VALUE; + return l; + } + else if( type == 1 ) + { + long l = tag.readShort(); + l -= Short.MIN_VALUE; + return l; + } + else if( type == 2 ) + { + long l = tag.readInt(); + l -= Integer.MIN_VALUE; + return l; + } + + return tag.readLong(); + } + + @Override + public long getStackSize() + { + return this.stackSize; + } + + @Override + public StackType setStackSize( long ss ) + { + this.stackSize = ss; + return (StackType) this; + } + + @Override + public long getCountRequestable() + { + return this.countRequestable; + } + + @Override + public StackType setCountRequestable( long countRequestable ) + { + this.countRequestable = countRequestable; + return (StackType) this; + } + + @Override + public boolean isCraftable() + { + return this.isCraftable; + } + + @Override + public StackType setCraftable( boolean isCraftable ) + { + this.isCraftable = isCraftable; + return (StackType) this; } @Override @@ -48,127 +107,39 @@ public abstract class AEStack implements IAEStack 0 || this.isCraftable; } @Override - public StackType setStackSize(long ss) - { - this.stackSize = ss; - return (StackType) this; - } - - @Override - public long getCountRequestable() - { - return this.countRequestable; - } - - @Override - public StackType setCountRequestable(long countRequestable) - { - this.countRequestable = countRequestable; - return (StackType) this; - } - - @Override - public boolean isCraftable() - { - return this.isCraftable; - } - - @Override - public StackType setCraftable(boolean isCraftable) - { - this.isCraftable = isCraftable; - return (StackType) this; - } - - @Override - public void decStackSize(long i) - { - this.stackSize -= i; - } - - @Override - public void incStackSize(long i) + public void incStackSize( long i ) { this.stackSize += i; } @Override - public void decCountRequestable(long i) + public void decStackSize( long i ) + { + this.stackSize -= i; + } + + @Override + public void incCountRequestable( long i ) + { + this.countRequestable += i; + } + + @Override + public void decCountRequestable( long i ) { this.countRequestable -= i; } @Override - public void incCountRequestable(long i) + public void writeToPacket( ByteBuf i ) throws IOException { - this.countRequestable += i; - } - - void putPacketValue(ByteBuf tag, long num) - { - if ( num <= 255 ) - tag.writeByte( (byte) (num + Byte.MIN_VALUE) ); - else if ( num <= 65535 ) - tag.writeShort( (short) (num + Short.MIN_VALUE) ); - else if ( num <= 4294967295L ) - tag.writeInt( (int) (num + Integer.MIN_VALUE) ); - else - tag.writeLong( num ); - } - - static long getPacketValue(byte type, ByteBuf tag) - { - if ( type == 0 ) - { - long l = tag.readByte(); - l -= Byte.MIN_VALUE; - return l; - } - else if ( type == 1 ) - { - long l = tag.readShort(); - l -= Short.MIN_VALUE; - return l; - } - else if ( type == 2 ) - { - long l = tag.readInt(); - l -= Integer.MIN_VALUE; - return l; - } - - return tag.readLong(); - } - - byte getType(long num) - { - if ( num <= 255 ) - return 0; - else if ( num <= 65535 ) - return 1; - else if ( num <= 4294967295L ) - return 2; - else - return 3; - } - - abstract void writeIdentity(ByteBuf i) throws IOException; - - abstract void readNBT(ByteBuf i) throws IOException; - - abstract boolean hasTagCompound(); - - @Override - public void writeToPacket(ByteBuf i) throws IOException - { - byte mask = (byte) (this.getType( 0 ) | (this.getType( this.stackSize ) << 2) | (this.getType( this.countRequestable ) << 4) | ((byte) (this.isCraftable ? 1 : 0) << 6) | (this.hasTagCompound() ? 1 - : 0) << 7); + byte mask = (byte) ( this.getType( 0 ) | ( this.getType( this.stackSize ) << 2 ) | ( this.getType( this.countRequestable ) << 4 ) | ( (byte) ( this.isCraftable ? 1 : 0 ) << 6 ) | ( this.hasTagCompound() ? 1 : 0 ) << 7 ); i.writeByte( mask ); this.writeIdentity( i ); @@ -180,4 +151,33 @@ public abstract class AEStack implements IAEStack implements IItemList clz; // private int currentPriority = Integer.MIN_VALUE; - - int iteration = Integer.MIN_VALUE; public Throwable stacktrace; + int iteration = Integer.MIN_VALUE; public ItemList( Class cla ) { this.clz = cla; } - private boolean checkStackType( StackType st ) - { - if ( st == null ) - return true; - - if ( !this.clz.isInstance( st ) ) - throw new RuntimeException( "WRONG TYPE - got " + st.getClass().getName() + " expected " + this.clz.getName() ); - - return false; - } - @Override synchronized public void add( StackType option ) { - if ( this.checkStackType( option ) ) + if( this.checkStackType( option ) ) return; StackType st = this.records.get( option ); - if ( st != null ) + if( st != null ) { // st.setPriority( currentPriority ); st.add( option ); return; } - StackType opt = ( StackType ) option.copy(); + StackType opt = (StackType) option.copy(); // opt.setPriority( currentPriority ); this.records.put( opt, opt ); } + private boolean checkStackType( StackType st ) + { + if( st == null ) + return true; + + if( !this.clz.isInstance( st ) ) + throw new RuntimeException( "WRONG TYPE - got " + st.getClass().getName() + " expected " + this.clz.getName() ); + + return false; + } + + @Override + synchronized public StackType findPrecise( StackType i ) + { + if( this.checkStackType( i ) ) + return null; + + StackType is = this.records.get( i ); + if( is != null ) + { + return is; + } + + return null; + } + + @Override + public Collection findFuzzy( StackType filter, FuzzyMode fuzzy ) + { + if( this.checkStackType( filter ) ) + return new ArrayList(); + + if( filter instanceof IAEFluidStack ) + { + List result = Lists.newArrayList(); + + if( filter.equals( this ) ) + { + result.add( filter ); + } + + return result; + } + + AEItemStack ais = (AEItemStack) filter; + if( ais.isOre() ) + { + OreReference or = ais.def.isOre; + if( or.getAEEquivalents().size() == 1 ) + { + IAEItemStack is = or.getAEEquivalents().get( 0 ); + return this.findFuzzyDamage( (AEItemStack) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ); + } + else + { + Collection output = new LinkedList(); + + for( IAEItemStack is : or.getAEEquivalents() ) + output.addAll( this.findFuzzyDamage( (AEItemStack) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) ); + + return output; + } + } + + return this.findFuzzyDamage( ais, fuzzy, false ); + } + + @Override + public boolean isEmpty() + { + return !this.iterator().hasNext(); + } + + public Collection findFuzzyDamage( AEItemStack filter, FuzzyMode fuzzy, boolean ignoreMeta ) + { + StackType low = (StackType) filter.getLow( fuzzy, ignoreMeta ); + StackType high = (StackType) filter.getHigh( fuzzy, ignoreMeta ); + return this.records.subMap( low, true, high, true ).descendingMap().values(); + } + @Override synchronized public void addStorage( StackType option ) // adds a stack as - // stored. + // stored. { - if ( this.checkStackType( option ) ) + if( this.checkStackType( option ) ) return; StackType st = this.records.get( option ); - if ( st != null ) + if( st != null ) { // st.setPriority( currentPriority ); st.incStackSize( option.getStackSize() ); return; } - StackType opt = ( StackType ) option.copy(); + StackType opt = (StackType) option.copy(); // opt.setPriority( currentPriority ); this.records.put( opt, opt ); } + /* + * synchronized public void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = + * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } + */ + @Override synchronized public void addCrafting( StackType option ) // adds a stack as - // craftable. + // craftable. { - if ( this.checkStackType( option ) ) + if( this.checkStackType( option ) ) return; StackType st = this.records.get( option ); - if ( st != null ) + if( st != null ) { // st.setPriority( currentPriority ); st.setCraftable( true ); return; } - StackType opt = ( StackType ) option.copy(); + StackType opt = (StackType) option.copy(); // opt.setPriority( currentPriority ); opt.setStackSize( 0 ); opt.setCraftable( true ); @@ -133,22 +205,22 @@ public final class ItemList implements IItemList implements IItemList i = iterator(); while (i.hasNext()) { StackType AEI = - * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } - */ - - @Override - synchronized public Iterator iterator() - { - return new MeaningfulIterator( this.records.values().iterator() ); - } - - @Override - synchronized public StackType findPrecise( StackType i ) - { - if ( this.checkStackType( i ) ) - return null; - - StackType is = this.records.get( i ); - if ( is != null ) - { - return is; - } - - return null; - } - @Override synchronized public int size() { @@ -207,56 +246,15 @@ public final class ItemList implements IItemList iterator() { - return !this.iterator().hasNext(); - } - - public Collection findFuzzyDamage( AEItemStack filter, FuzzyMode fuzzy, boolean ignoreMeta ) - { - StackType low = ( StackType ) filter.getLow( fuzzy, ignoreMeta ); - StackType high = ( StackType ) filter.getHigh( fuzzy, ignoreMeta ); - return this.records.subMap( low, true, high, true ).descendingMap().values(); + return new MeaningfulIterator( this.records.values().iterator() ); } @Override - public Collection findFuzzy( StackType filter, FuzzyMode fuzzy ) + synchronized public void resetStatus() { - if ( this.checkStackType( filter ) ) - return new ArrayList(); - - if ( filter instanceof IAEFluidStack ) - { - List result = Lists.newArrayList(); - - if ( filter.equals( this ) ) - { - result.add( filter ); - } - - return result; - } - - AEItemStack ais = ( AEItemStack ) filter; - if ( ais.isOre() ) - { - OreReference or = ais.def.isOre; - if ( or.getAEEquivalents().size() == 1 ) - { - IAEItemStack is = or.getAEEquivalents().get( 0 ); - return this.findFuzzyDamage( ( AEItemStack ) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ); - } - else - { - Collection output = new LinkedList(); - - for ( IAEItemStack is : or.getAEEquivalents() ) - output.addAll( this.findFuzzyDamage( ( AEItemStack ) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) ); - - return output; - } - } - - return this.findFuzzyDamage( ais, fuzzy, false ); + for( StackType i : this ) + i.reset(); } } diff --git a/src/main/java/appeng/util/item/ItemModList.java b/src/main/java/appeng/util/item/ItemModList.java index b316f8060..f8f7cba10 100644 --- a/src/main/java/appeng/util/item/ItemModList.java +++ b/src/main/java/appeng/util/item/ItemModList.java @@ -18,6 +18,7 @@ package appeng.util.item; + import java.util.Collection; import appeng.api.AEApi; @@ -25,24 +26,26 @@ import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemContainer; + public class ItemModList implements IItemContainer { final IItemContainer backingStore; final IItemContainer overrides = AEApi.instance().storage().createItemList(); - public ItemModList(IItemContainer backend) { + public ItemModList( IItemContainer backend ) + { this.backingStore = backend; } @Override - public void add(IAEItemStack option) + public void add( IAEItemStack option ) { IAEItemStack over = this.overrides.findPrecise( option ); - if ( over == null ) + if( over == null ) { over = this.backingStore.findPrecise( option ); - if ( over == null ) + if( over == null ) this.overrides.add( option ); else { @@ -55,16 +58,16 @@ public class ItemModList implements IItemContainer } @Override - public IAEItemStack findPrecise(IAEItemStack i) + public IAEItemStack findPrecise( IAEItemStack i ) { IAEItemStack over = this.overrides.findPrecise( i ); - if ( over == null ) + if( over == null ) return this.backingStore.findPrecise( i ); return over; } @Override - public Collection findFuzzy(IAEItemStack input, FuzzyMode fuzzy) + public Collection findFuzzy( IAEItemStack input, FuzzyMode fuzzy ) { return this.overrides.findFuzzy( input, fuzzy ); } @@ -74,5 +77,4 @@ public class ItemModList implements IItemContainer { return this.overrides.isEmpty() && this.backingStore.isEmpty(); } - } diff --git a/src/main/java/appeng/util/item/MeaningfulIterator.java b/src/main/java/appeng/util/item/MeaningfulIterator.java index 18941f670..3f0597d67 100644 --- a/src/main/java/appeng/util/item/MeaningfulIterator.java +++ b/src/main/java/appeng/util/item/MeaningfulIterator.java @@ -18,17 +18,19 @@ package appeng.util.item; + import java.util.Iterator; import appeng.api.storage.data.IAEStack; + public class MeaningfulIterator implements Iterator { private final Iterator parent; private StackType next; - public MeaningfulIterator(Iterator iterator) + public MeaningfulIterator( Iterator iterator ) { this.parent = iterator; } @@ -36,10 +38,10 @@ public class MeaningfulIterator implements Iterator< @Override public boolean hasNext() { - while (this.parent.hasNext()) + while( this.parent.hasNext() ) { this.next = this.parent.next(); - if ( this.next.isMeaningful() ) + if( this.next.isMeaningful() ) { return true; } @@ -63,5 +65,4 @@ public class MeaningfulIterator implements Iterator< { this.parent.remove(); } - } diff --git a/src/main/java/appeng/util/item/OreHelper.java b/src/main/java/appeng/util/item/OreHelper.java index d55e3eca7..3bc7d475d 100644 --- a/src/main/java/appeng/util/item/OreHelper.java +++ b/src/main/java/appeng/util/item/OreHelper.java @@ -45,14 +45,14 @@ public class OreHelper /** * A local cache to speed up OreDictionary lookups. */ - private final LoadingCache> oreDictCache = CacheBuilder - .newBuilder().build( new CacheLoader>(){ - @Override - public List load( String oreName ) - { - return OreDictionary.getOres( oreName ); - } - } ); + private final LoadingCache> oreDictCache = CacheBuilder.newBuilder().build( new CacheLoader>() + { + @Override + public List load( String oreName ) + { + return OreDictionary.getOres( oreName ); + } + } ); private final Map references = new HashMap(); @@ -60,13 +60,14 @@ public class OreHelper * Test if the passed {@link ItemStack} is an ore. * * @param ItemStack the itemstack to test + * * @return true if an ore entry exists, false otherwise */ public OreReference isOre( ItemStack ItemStack ) { ItemRef ir = new ItemRef( ItemStack ); - if ( !this.references.containsKey( ir ) ) + if( !this.references.containsKey( ir ) ) { final OreReference ref = new OreReference(); final Collection ores = ref.getOres(); @@ -74,17 +75,17 @@ public class OreHelper Set toAdd = new HashSet(); - for ( String ore : OreDictionary.getOreNames() ) + for( String ore : OreDictionary.getOreNames() ) { // skip ore if it is a match already or null. - if ( ore == null || toAdd.contains( ore ) ) + if( ore == null || toAdd.contains( ore ) ) { continue; } - for ( ItemStack oreItem : this.oreDictCache.getUnchecked( ore ) ) + for( ItemStack oreItem : this.oreDictCache.getUnchecked( ore ) ) { - if ( OreDictionary.itemMatches( oreItem, ItemStack, false ) ) + if( OreDictionary.itemMatches( oreItem, ItemStack, false ) ) { toAdd.add( ore ); break; @@ -92,13 +93,13 @@ public class OreHelper } } - for ( String ore : toAdd ) + for( String ore : toAdd ) { set.add( ore ); ores.add( OreDictionary.getOreID( ore ) ); } - if ( !set.isEmpty() ) + if( !set.isEmpty() ) this.references.put( ir, ref ); else this.references.put( ir, null ); @@ -117,16 +118,16 @@ public class OreHelper public boolean sameOre( OreReference a, OreReference b ) { - if ( a == null || b == null ) + if( a == null || b == null ) return false; - if ( a == b ) + if( a == b ) return true; Collection bOres = b.getOres(); - for ( Integer ore : a.getOres() ) + for( Integer ore : a.getOres() ) { - if ( bOres.contains( ore ) ) + if( bOres.contains( ore ) ) return true; } @@ -136,14 +137,14 @@ public class OreHelper public boolean sameOre( AEItemStack aeItemStack, ItemStack o ) { OreReference a = aeItemStack.def.isOre; - if ( a == null ) + if( a == null ) return false; - for ( String oreName : a.getEquivalents() ) + for( String oreName : a.getEquivalents() ) { - for ( ItemStack oreItem : this.oreDictCache.getUnchecked( oreName ) ) + for( ItemStack oreItem : this.oreDictCache.getUnchecked( oreName ) ) { - if ( OreDictionary.itemMatches( oreItem, o, false ) ) + if( OreDictionary.itemMatches( oreItem, o, false ) ) return true; } } @@ -159,11 +160,15 @@ public class OreHelper private static class ItemRef { + private final Item ref; + private final int damage; + private final int hash; + ItemRef( ItemStack stack ) { this.ref = stack.getItem(); - if ( stack.getItem().isDamageable() ) + if( stack.getItem().isDamageable() ) this.damage = 0; // IGNORED else this.damage = stack.getItemDamage(); // might be important... @@ -171,32 +176,27 @@ public class OreHelper this.hash = this.ref.hashCode() ^ this.damage; } - private final Item ref; - private final int damage; - private final int hash; - - @Override - public boolean equals( Object obj ) - { - if ( obj == null ) - return false; - if ( this.getClass() != obj.getClass() ) - return false; - ItemRef other = ( ItemRef ) obj; - return this.damage == other.damage && this.ref == other.ref; - } - @Override public int hashCode() { return this.hash; } + @Override + public boolean equals( Object obj ) + { + if( obj == null ) + return false; + if( this.getClass() != obj.getClass() ) + return false; + ItemRef other = (ItemRef) obj; + return this.damage == other.damage && this.ref == other.ref; + } + @Override public String toString() { return "ItemRef [ref=" + this.ref.getUnlocalizedName() + ", damage=" + this.damage + ", hash=" + this.hash + ']'; } - } } \ No newline at end of file diff --git a/src/main/java/appeng/util/item/OreReference.java b/src/main/java/appeng/util/item/OreReference.java index 32eed766d..d7c643725 100644 --- a/src/main/java/appeng/util/item/OreReference.java +++ b/src/main/java/appeng/util/item/OreReference.java @@ -35,8 +35,8 @@ public class OreReference { private final List otherOptions = new LinkedList(); - private List aeOtherOptions = null; private final Set ores = new HashSet(); + private List aeOtherOptions = null; public Collection getEquivalents() { @@ -45,20 +45,19 @@ public class OreReference public List getAEEquivalents() { - if ( this.aeOtherOptions == null ) + if( this.aeOtherOptions == null ) { this.aeOtherOptions = new ArrayList( this.otherOptions.size() ); // SUMMON AE STACKS! - for ( String oreName : this.otherOptions ) + for( String oreName : this.otherOptions ) { - for ( ItemStack is : OreHelper.INSTANCE.getCachedOres( oreName ) ) + for( ItemStack is : OreHelper.INSTANCE.getCachedOres( oreName ) ) { - if ( is.getItem() != null ) + if( is.getItem() != null ) { this.aeOtherOptions.add( AEItemStack.create( is ) ); } - } } } @@ -70,5 +69,4 @@ public class OreReference { return this.ores; } - } diff --git a/src/main/java/appeng/util/item/SharedSearchObject.java b/src/main/java/appeng/util/item/SharedSearchObject.java index 53b2d15bf..e7883fa8e 100644 --- a/src/main/java/appeng/util/item/SharedSearchObject.java +++ b/src/main/java/appeng/util/item/SharedSearchObject.java @@ -18,44 +18,46 @@ package appeng.util.item; + import net.minecraft.item.Item; import net.minecraft.nbt.NBTTagCompound; import appeng.util.Platform; + public class SharedSearchObject { final int def; final int hash; - NBTTagCompound compound; public AESharedNBT shared; + NBTTagCompound compound; - public SharedSearchObject(Item itemID, int damageValue, NBTTagCompound tagCompound) { - this.def = (damageValue << Platform.DEF_OFFSET) | Item.itemRegistry.getIDForObject( itemID ); + public SharedSearchObject( Item itemID, int damageValue, NBTTagCompound tagCompound ) + { + this.def = ( damageValue << Platform.DEF_OFFSET ) | Item.itemRegistry.getIDForObject( itemID ); this.hash = Platform.NBTOrderlessHash( tagCompound ); this.compound = tagCompound; } - @Override - public boolean equals(Object obj) - { - if ( obj == null ) - return false; - if ( this.getClass() != obj.getClass() ) - return false; - SharedSearchObject other = (SharedSearchObject) obj; - if ( this.def == other.def && this.hash == other.hash ) - { - return Platform.NBTEqualityTest( this.compound, other.compound ); - } - return false; - } - @Override public int hashCode() { return this.def ^ this.hash; } + @Override + public boolean equals( Object obj ) + { + if( obj == null ) + return false; + if( this.getClass() != obj.getClass() ) + return false; + SharedSearchObject other = (SharedSearchObject) obj; + if( this.def == other.def && this.hash == other.hash ) + { + return Platform.NBTEqualityTest( this.compound, other.compound ); + } + return false; + } } diff --git a/src/main/java/appeng/util/iterators/AEInvIterator.java b/src/main/java/appeng/util/iterators/AEInvIterator.java index 30fbd91d4..dbaeedd68 100644 --- a/src/main/java/appeng/util/iterators/AEInvIterator.java +++ b/src/main/java/appeng/util/iterators/AEInvIterator.java @@ -18,11 +18,13 @@ package appeng.util.iterators; + import java.util.Iterator; import appeng.api.storage.data.IAEItemStack; import appeng.tile.inventory.AppEngInternalAEInventory; + public class AEInvIterator implements Iterator { @@ -31,7 +33,8 @@ public class AEInvIterator implements Iterator int x = 0; - public AEInvIterator(AppEngInternalAEInventory i) { + public AEInvIterator( AppEngInternalAEInventory i ) + { this.inv = i; this.size = this.inv.getSizeInventory(); } @@ -55,5 +58,4 @@ public class AEInvIterator implements Iterator { throw new RuntimeException( "no..." ); } - } diff --git a/src/main/java/appeng/util/iterators/ChainedIterator.java b/src/main/java/appeng/util/iterators/ChainedIterator.java index f43f1e5ac..6cbb82660 100644 --- a/src/main/java/appeng/util/iterators/ChainedIterator.java +++ b/src/main/java/appeng/util/iterators/ChainedIterator.java @@ -18,15 +18,18 @@ package appeng.util.iterators; + import java.util.Iterator; + public class ChainedIterator implements Iterator { - int offset = 0; final T[] list; + int offset = 0; - public ChainedIterator(T... list) { + public ChainedIterator( T... list ) + { this.list = list; } @@ -49,5 +52,4 @@ public class ChainedIterator implements Iterator { throw new RuntimeException( "Not implemented." ); } - } diff --git a/src/main/java/appeng/util/iterators/InvIterator.java b/src/main/java/appeng/util/iterators/InvIterator.java index b1d2983da..e27004f35 100644 --- a/src/main/java/appeng/util/iterators/InvIterator.java +++ b/src/main/java/appeng/util/iterators/InvIterator.java @@ -18,11 +18,13 @@ package appeng.util.iterators; + import java.util.Iterator; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; + public class InvIterator implements Iterator { @@ -31,7 +33,8 @@ public class InvIterator implements Iterator int x = 0; - public InvIterator(IInventory i) { + public InvIterator( IInventory i ) + { this.inv = i; this.size = this.inv.getSizeInventory(); } @@ -55,5 +58,4 @@ public class InvIterator implements Iterator { throw new RuntimeException( "no..." ); } - } diff --git a/src/main/java/appeng/util/iterators/NullIterator.java b/src/main/java/appeng/util/iterators/NullIterator.java index 329871f95..3ce3edcc5 100644 --- a/src/main/java/appeng/util/iterators/NullIterator.java +++ b/src/main/java/appeng/util/iterators/NullIterator.java @@ -18,8 +18,10 @@ package appeng.util.iterators; + import java.util.Iterator; + public class NullIterator implements Iterator { @@ -40,5 +42,4 @@ public class NullIterator implements Iterator { } - } diff --git a/src/main/java/appeng/util/iterators/ProxyNodeIterator.java b/src/main/java/appeng/util/iterators/ProxyNodeIterator.java index 58d3c1373..dc8b8f956 100644 --- a/src/main/java/appeng/util/iterators/ProxyNodeIterator.java +++ b/src/main/java/appeng/util/iterators/ProxyNodeIterator.java @@ -18,6 +18,7 @@ package appeng.util.iterators; + import java.util.Iterator; import net.minecraftforge.common.util.ForgeDirection; @@ -25,12 +26,14 @@ import net.minecraftforge.common.util.ForgeDirection; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; + public class ProxyNodeIterator implements Iterator { final Iterator hosts; - public ProxyNodeIterator(Iterator hosts) { + public ProxyNodeIterator( Iterator hosts ) + { this.hosts = hosts; } @@ -52,5 +55,4 @@ public class ProxyNodeIterator implements Iterator { throw new RuntimeException( "Not implemented." ); } - } diff --git a/src/main/java/appeng/util/iterators/StackToSlotIterator.java b/src/main/java/appeng/util/iterators/StackToSlotIterator.java index dfa46eb36..397e483c3 100644 --- a/src/main/java/appeng/util/iterators/StackToSlotIterator.java +++ b/src/main/java/appeng/util/iterators/StackToSlotIterator.java @@ -18,20 +18,23 @@ package appeng.util.iterators; + import java.util.Iterator; import net.minecraft.item.ItemStack; import appeng.util.inv.ItemSlot; + public class StackToSlotIterator implements Iterator { - int x = 0; final ItemSlot iss = new ItemSlot(); final Iterator is; + int x = 0; - public StackToSlotIterator(Iterator is) { + public StackToSlotIterator( Iterator is ) + { this.is = is; } @@ -55,5 +58,4 @@ public class StackToSlotIterator implements Iterator { // uhh no. } - } diff --git a/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java b/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java index e044ba1e0..cd8394f4e 100644 --- a/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java @@ -18,18 +18,20 @@ package appeng.util.prioitylist; + import java.util.ArrayList; import java.util.List; import appeng.api.storage.data.IAEStack; + public class DefaultPriorityList> implements IPartitionList { final static List NULL_LIST = new ArrayList(); @Override - public boolean isListed(T input) + public boolean isListed( T input ) { return false; } @@ -45,5 +47,4 @@ public class DefaultPriorityList> implements IPartitionLis { return NULL_LIST; } - } diff --git a/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java b/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java index 76df7ac76..bdcd3e9d1 100644 --- a/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java @@ -18,25 +18,28 @@ package appeng.util.prioitylist; + import java.util.Collection; import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; + public class FuzzyPriorityList> implements IPartitionList { final IItemList list; final FuzzyMode mode; - public FuzzyPriorityList(IItemList in, FuzzyMode mode) { + public FuzzyPriorityList( IItemList in, FuzzyMode mode ) + { this.list = in; this.mode = mode; } @Override - public boolean isListed(T input) + public boolean isListed( T input ) { Collection out = this.list.findFuzzy( input, this.mode ); return out != null && !out.isEmpty(); @@ -53,5 +56,4 @@ public class FuzzyPriorityList> implements IPartitionList< { return this.list; } - } diff --git a/src/main/java/appeng/util/prioitylist/IPartitionList.java b/src/main/java/appeng/util/prioitylist/IPartitionList.java index 9bb429582..2981f0918 100644 --- a/src/main/java/appeng/util/prioitylist/IPartitionList.java +++ b/src/main/java/appeng/util/prioitylist/IPartitionList.java @@ -18,15 +18,16 @@ package appeng.util.prioitylist; + import appeng.api.storage.data.IAEStack; + public interface IPartitionList> { - boolean isListed(T input); + boolean isListed( T input ); boolean isEmpty(); Iterable getItems(); - } diff --git a/src/main/java/appeng/util/prioitylist/MergedPriorityList.java b/src/main/java/appeng/util/prioitylist/MergedPriorityList.java index 96dfc38cf..4eed91c6c 100644 --- a/src/main/java/appeng/util/prioitylist/MergedPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/MergedPriorityList.java @@ -18,36 +18,38 @@ package appeng.util.prioitylist; + import java.util.ArrayList; import java.util.List; import appeng.api.storage.data.IAEStack; + public class MergedPriorityList> implements IPartitionList { final List> positive = new ArrayList>(); final List> negative = new ArrayList>(); - public void addNewList(IPartitionList list, boolean isWhitelist) + public void addNewList( IPartitionList list, boolean isWhitelist ) { - if ( isWhitelist ) + if( isWhitelist ) this.positive.add( list ); else this.negative.add( list ); } @Override - public boolean isListed(T input) + public boolean isListed( T input ) { - for (IPartitionList l : this.negative) - if ( l.isListed( input ) ) + for( IPartitionList l : this.negative ) + if( l.isListed( input ) ) return false; - if ( !this.positive.isEmpty() ) + if( !this.positive.isEmpty() ) { - for (IPartitionList l : this.positive) - if ( l.isListed( input ) ) + for( IPartitionList l : this.positive ) + if( l.isListed( input ) ) return true; return false; @@ -67,5 +69,4 @@ public class MergedPriorityList> implements IPartitionList { throw new RuntimeException( "Not Implemented" ); } - } diff --git a/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java b/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java index 1a507bbdc..c34ff151a 100644 --- a/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java +++ b/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java @@ -18,20 +18,23 @@ package appeng.util.prioitylist; + import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; + public class PrecisePriorityList> implements IPartitionList { final IItemList list; - public PrecisePriorityList(IItemList in) { + public PrecisePriorityList( IItemList in ) + { this.list = in; } @Override - public boolean isListed(T input) + public boolean isListed( T input ) { return this.list.findPrecise( input ) != null; } @@ -47,5 +50,4 @@ public class PrecisePriorityList> implements IPartitionLis { return this.list; } - } diff --git a/src/main/java/appeng/worldgen/MeteoritePlacer.java b/src/main/java/appeng/worldgen/MeteoritePlacer.java index 80738d67d..28645b83d 100644 --- a/src/main/java/appeng/worldgen/MeteoritePlacer.java +++ b/src/main/java/appeng/worldgen/MeteoritePlacer.java @@ -43,14 +43,14 @@ import appeng.api.definitions.IMaterials; import appeng.core.AEConfig; import appeng.core.WorldSettings; import appeng.core.features.AEFeature; +import appeng.util.InventoryAdaptor; +import appeng.util.Platform; import appeng.worldgen.meteorite.Fallout; import appeng.worldgen.meteorite.FalloutCopy; import appeng.worldgen.meteorite.FalloutSand; import appeng.worldgen.meteorite.FalloutSnow; import appeng.worldgen.meteorite.IMeteoriteWorld; import appeng.worldgen.meteorite.MeteoriteBlockPutter; -import appeng.util.InventoryAdaptor; -import appeng.util.Platform; public final class MeteoritePlacer @@ -91,7 +91,7 @@ public final class MeteoritePlacer this.validSpawn.add( Blocks.ice ); this.validSpawn.add( Blocks.snow ); - for ( Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) + for( Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) { this.invalidSpawn.add( skyStoneBlock ); } @@ -123,23 +123,23 @@ public final class MeteoritePlacer Block blk = Block.getBlockById( this.settings.getInteger( "blk" ) ); - if ( blk == Blocks.sand ) + if( blk == Blocks.sand ) this.type = new FalloutSand( w, x, y, z, this.putter, this.skyStoneDefinition ); - else if ( blk == Blocks.hardened_clay ) + else if( blk == Blocks.hardened_clay ) this.type = new FalloutCopy( w, x, y, z, this.putter, this.skyStoneDefinition ); - else if ( blk == Blocks.ice || blk == Blocks.snow ) + else if( blk == Blocks.ice || blk == Blocks.snow ) this.type = new FalloutSnow( w, x, y, z, this.putter, this.skyStoneDefinition ); int skyMode = this.settings.getInteger( "skyMode" ); // creator - if ( skyMode > 10 ) + if( skyMode > 10 ) this.placeCrater( w, x, y, z ); this.placeMeteorite( w, x, y, z ); // collapse blocks... - if ( skyMode > 3 ) + if( skyMode > 3 ) this.decay( w, x, y, z ); w.done(); @@ -156,12 +156,12 @@ public final class MeteoritePlacer int minZ = w.minZ( z - 200 ); int maxZ = w.maxZ( z + 200 ); - for ( int j = y - 5; j < maxY; j++ ) + for( int j = y - 5; j < maxY; j++ ) { boolean changed = false; - for ( int i = minX; i < maxX; i++ ) - for ( int k = minZ; k < maxZ; k++ ) + for( int i = minX; i < maxX; i++ ) + for( int k = minZ; k < maxZ; k++ ) { double dx = i - x; double dz = k - z; @@ -169,11 +169,11 @@ public final class MeteoritePlacer double distanceFrom = dx * dx + dz * dz; - if ( j > h + distanceFrom * 0.02 ) + if( j > h + distanceFrom * 0.02 ) { - if ( lava && j < y && w.getBlock( x, y - 1, z ).isBlockSolid( w.getWorld(), i, j, k, 0 ) ) + if( lava && j < y && w.getBlock( x, y - 1, z ).isBlockSolid( w.getWorld(), i, j, k, 0 ) ) { - if ( j > h + distanceFrom * 0.02 ) + if( j > h + distanceFrom * 0.02 ) this.putter.put( w, i, j, k, Blocks.lava ); } else @@ -182,7 +182,7 @@ public final class MeteoritePlacer } } - for ( Object o : w.getWorld().getEntitiesWithinAABB( EntityItem.class, AxisAlignedBB.getBoundingBox( w.minX( x - 30 ), y - 5, w.minZ( z - 30 ), w.maxX( x + 30 ), y + 30, w.maxZ( z + 30 ) ) ) ) + for( Object o : w.getWorld().getEntitiesWithinAABB( EntityItem.class, AxisAlignedBB.getBoundingBox( w.minX( x - 30 ), y - 5, w.minZ( z - 30 ), w.maxX( x + 30 ), y + 30, w.maxZ( z + 30 ) ) ) ) { Entity e = (Entity) o; e.setDead(); @@ -197,41 +197,41 @@ public final class MeteoritePlacer int meteorZHeight = w.maxZ( z + 8 ); // spawn meteor - for ( int i = meteorXLength; i < meteorXHeight; i++ ) - for ( int j = y - 8; j < y + 8; j++ ) - for ( int k = meteorZLength; k < meteorZHeight; k++ ) + for( int i = meteorXLength; i < meteorXHeight; i++ ) + for( int j = y - 8; j < y + 8; j++ ) + for( int k = meteorZLength; k < meteorZHeight; k++ ) { double dx = i - x; double dy = j - y; double dz = k - z; - if ( dx * dx * 0.7 + dy * dy * ( j > y ? 1.4 : 0.8 ) + dz * dz * 0.7 < this.squaredMeteoriteSize ) + if( dx * dx * 0.7 + dy * dy * ( j > y ? 1.4 : 0.8 ) + dz * dz * 0.7 < this.squaredMeteoriteSize ) { - for ( Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) + for( Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) { this.putter.put( w, i, j, k, skyStoneBlock ); } } } - if ( AEConfig.instance.isFeatureEnabled( AEFeature.SpawnPressesInMeteorites ) ) + if( AEConfig.instance.isFeatureEnabled( AEFeature.SpawnPressesInMeteorites ) ) { - for ( Block skyChestBlock : this.skyChestDefinition.maybeBlock().asSet() ) + for( Block skyChestBlock : this.skyChestDefinition.maybeBlock().asSet() ) { this.putter.put( w, x, y, z, skyChestBlock ); } TileEntity te = w.getTileEntity( x, y, z ); - if ( te instanceof IInventory ) + if( te instanceof IInventory ) { InventoryAdaptor ap = InventoryAdaptor.getAdaptor( te, ForgeDirection.UP ); int primary = Math.max( 1, (int) ( Math.random() * 4 ) ); - if ( primary > 3 ) // in case math breaks... + if( primary > 3 ) // in case math breaks... primary = 3; - for ( int zz = 0; zz < primary; zz++ ) + for( int zz = 0; zz < primary; zz++ ) { int r = 0; boolean duplicate = false; @@ -240,7 +240,7 @@ public final class MeteoritePlacer { duplicate = false; - if ( Math.random() > PRESSES_SPAWN_CHANCE ) + if( Math.random() > PRESSES_SPAWN_CHANCE ) r = WorldSettings.getInstance().getNextOrderedValue( "presses" ); else r = (int) ( Math.random() * 1000 ); @@ -248,28 +248,28 @@ public final class MeteoritePlacer ItemStack toAdd = null; final IMaterials materials = AEApi.instance().definitions().materials(); - switch ( r % 4 ) + switch( r % 4 ) { case 0: - for ( ItemStack calc : materials.calcProcessorPress().maybeStack( 1 ).asSet() ) + for( ItemStack calc : materials.calcProcessorPress().maybeStack( 1 ).asSet() ) { toAdd = calc; } break; case 1: - for ( ItemStack calc : materials.engProcessorPress().maybeStack( 1 ).asSet() ) + for( ItemStack calc : materials.engProcessorPress().maybeStack( 1 ).asSet() ) { toAdd = calc; } break; case 2: - for ( ItemStack calc : materials.logicProcessorPress().maybeStack( 1 ).asSet() ) + for( ItemStack calc : materials.logicProcessorPress().maybeStack( 1 ).asSet() ) { toAdd = calc; } break; case 3: - for ( ItemStack calc : materials.siliconPress().maybeStack( 1 ).asSet() ) + for( ItemStack calc : materials.siliconPress().maybeStack( 1 ).asSet() ) { toAdd = calc; } @@ -277,25 +277,25 @@ public final class MeteoritePlacer default: } - if ( toAdd != null ) + if( toAdd != null ) { - if ( ap.simulateRemove( 1, toAdd, null ) == null ) + if( ap.simulateRemove( 1, toAdd, null ) == null ) ap.addItems( toAdd ); else duplicate = true; } } - while ( duplicate ); + while( duplicate ); } int secondary = Math.max( 1, (int) ( Math.random() * 3 ) ); - for ( int zz = 0; zz < secondary; zz++ ) + for( int zz = 0; zz < secondary; zz++ ) { - switch ( (int) ( Math.random() * 1000 ) % 3 ) + switch( (int) ( Math.random() * 1000 ) % 3 ) { case 0: final int amount = (int) ( ( Math.random() * SKYSTONE_SPAWN_LIMIT ) + 1 ); - for ( ItemStack skyStoneStack : this.skyStoneDefinition.maybeStack( amount ).asSet() ) + for( ItemStack skyStoneStack : this.skyStoneDefinition.maybeStack( amount ).asSet() ) { ap.addItems( skyStoneStack ); } @@ -314,7 +314,7 @@ public final class MeteoritePlacer possibles.add( new ItemStack( net.minecraft.init.Items.gold_nugget ) ); ItemStack nugget = Platform.pickRandom( possibles ); - if ( nugget != null ) + if( nugget != null ) { nugget = nugget.copy(); nugget.stackSize = (int) ( Math.random() * 12 ) + 1; @@ -336,27 +336,27 @@ public final class MeteoritePlacer int meteorZLength = w.minZ( z - 30 ); int meteorZHeight = w.maxZ( z + 30 ); - for ( int i = meteorXLength; i < meteorXHeight; i++ ) - for ( int k = meteorZLength; k < meteorZHeight; k++ ) - for ( int j = y - 9; j < y + 30; j++ ) + for( int i = meteorXLength; i < meteorXHeight; i++ ) + for( int k = meteorZLength; k < meteorZHeight; k++ ) + for( int j = y - 9; j < y + 30; j++ ) { Block blk = w.getBlock( i, j, k ); - if ( blk == Blocks.lava ) + if( blk == Blocks.lava ) continue; - if ( blk.isReplaceable( w.getWorld(), i, j, k ) ) + if( blk.isReplaceable( w.getWorld(), i, j, k ) ) { blk = Platform.AIR; Block blk_b = w.getBlock( i, j + 1, k ); - if ( blk_b != blk ) + if( blk_b != blk ) { int meta_b = w.getBlockMetadata( i, j + 1, k ); w.setBlock( i, j, k, blk_b, meta_b, 3 ); w.setBlock( i, j + 1, k, blk ); } - else if ( randomShit < 100 * this.crater ) + else if( randomShit < 100 * this.crater ) { double dx = i - x; double dy = j - y; @@ -364,12 +364,12 @@ public final class MeteoritePlacer double dist = dx * dx + dy * dy + dz * dz; Block xf = w.getBlock( i, j - 1, k ); - if ( !xf.isReplaceable( w.getWorld(), i, j - 1, k ) ) + if( !xf.isReplaceable( w.getWorld(), i, j - 1, k ) ) { double extraRange = Math.random() * 0.6; double height = this.crater * ( extraRange + 0.2 ) - Math.abs( dist - this.crater * 1.7 ); - if ( xf != blk && height > 0 && Math.random() > 0.6 ) + if( xf != blk && height > 0 && Math.random() > 0.6 ) { randomShit++; this.type.getRandomFall( w, i, j, k ); @@ -381,15 +381,15 @@ public final class MeteoritePlacer { // decay. Block blk_b = w.getBlock( i, j + 1, k ); - if ( blk_b == Platform.AIR ) + if( blk_b == Platform.AIR ) { - if ( Math.random() > 0.4 ) + if( Math.random() > 0.4 ) { double dx = i - x; double dy = j - y; double dz = k - z; - if ( dx * dx + dy * dy + dz * dz < this.crater * 1.6 ) + if( dx * dx + dy * dy + dz * dz < this.crater * 1.6 ) { this.type.getRandomInset( w, i, j, k ); } @@ -411,11 +411,11 @@ public final class MeteoritePlacer { int validBlocks = 0; - if ( !w.hasNoSky() ) + if( !w.hasNoSky() ) return false; Block blk = w.getBlock( x, y, z ); - if ( !this.validSpawn.contains( blk ) ) + if( !this.validSpawn.contains( blk ) ) return false; // must spawn on a valid block.. this.settings = new NBTTagCompound(); @@ -431,68 +431,68 @@ public final class MeteoritePlacer this.settings.setBoolean( "lava", Math.random() > 0.9 ); - if ( blk == Blocks.sand ) + if( blk == Blocks.sand ) this.type = new FalloutSand( w, x, y, z, this.putter, this.skyStoneDefinition ); - else if ( blk == Blocks.hardened_clay ) + else if( blk == Blocks.hardened_clay ) this.type = new FalloutCopy( w, x, y, z, this.putter, this.skyStoneDefinition ); - else if ( blk == Blocks.ice || blk == Blocks.snow ) + else if( blk == Blocks.ice || blk == Blocks.snow ) this.type = new FalloutSnow( w, x, y, z, this.putter, this.skyStoneDefinition ); int realValidBlocks = 0; - for ( int i = x - 6; i < x + 6; i++ ) - for ( int j = y - 6; j < y + 6; j++ ) - for ( int k = z - 6; k < z + 6; k++ ) + for( int i = x - 6; i < x + 6; i++ ) + for( int j = y - 6; j < y + 6; j++ ) + for( int k = z - 6; k < z + 6; k++ ) { blk = w.getBlock( i, j, k ); - if ( this.validSpawn.contains( blk ) ) + if( this.validSpawn.contains( blk ) ) realValidBlocks++; } - for ( int i = x - 15; i < x + 15; i++ ) - for ( int j = y - 15; j < y + 15; j++ ) - for ( int k = z - 15; k < z + 15; k++ ) + for( int i = x - 15; i < x + 15; i++ ) + for( int j = y - 15; j < y + 15; j++ ) + for( int k = z - 15; k < z + 15; k++ ) { blk = w.getBlock( i, j, k ); - if ( this.invalidSpawn.contains( blk ) ) + if( this.invalidSpawn.contains( blk ) ) return false; - if ( this.validSpawn.contains( blk ) ) + if( this.validSpawn.contains( blk ) ) validBlocks++; } int minBLocks = 200; - if ( validBlocks > minBLocks && realValidBlocks > 80 ) + if( validBlocks > minBLocks && realValidBlocks > 80 ) { // we can spawn here! int skyMode = 0; - for ( int i = x - 15; i < x + 15; i++ ) - for ( int j = y - 15; j < y + 11; j++ ) - for ( int k = z - 15; k < z + 15; k++ ) + for( int i = x - 15; i < x + 15; i++ ) + for( int j = y - 15; j < y + 11; j++ ) + for( int k = z - 15; k < z + 15; k++ ) { - if ( w.canBlockSeeTheSky( i, j, k ) ) + if( w.canBlockSeeTheSky( i, j, k ) ) skyMode++; } boolean solid = true; - for ( int j = y - 15; j < y - 1; j++ ) + for( int j = y - 15; j < y - 1; j++ ) { - if ( w.getBlock( x, j, z ) == Platform.AIR ) + if( w.getBlock( x, j, z ) == Platform.AIR ) solid = false; } - if ( !solid ) + if( !solid ) skyMode = 0; // creator - if ( skyMode > 10 ) + if( skyMode > 10 ) this.placeCrater( w, x, y, z ); this.placeMeteorite( w, x, y, z ); // collapse blocks... - if ( skyMode > 3 ) + if( skyMode > 3 ) this.decay( w, x, y, z ); this.settings.setInteger( "skyMode", skyMode ); diff --git a/src/main/java/appeng/worldgen/MeteoriteWorldGen.java b/src/main/java/appeng/worldgen/MeteoriteWorldGen.java index d519b02ad..2090265ca 100644 --- a/src/main/java/appeng/worldgen/MeteoriteWorldGen.java +++ b/src/main/java/appeng/worldgen/MeteoriteWorldGen.java @@ -37,18 +37,19 @@ import appeng.hooks.TickHandler; import appeng.util.Platform; import appeng.worldgen.meteorite.ChunkOnly; + final public class MeteoriteWorldGen implements IWorldGenerator { @Override - public void generate(Random r, int chunkX, int chunkZ, World w, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) + public void generate( Random r, int chunkX, int chunkZ, World w, IChunkProvider chunkGenerator, IChunkProvider chunkProvider ) { - if ( WorldGenRegistry.INSTANCE.isWorldGenEnabled( WorldGenType.Meteorites, w ) ) + if( WorldGenRegistry.INSTANCE.isWorldGenEnabled( WorldGenType.Meteorites, w ) ) { // add new meteorites? - if ( r.nextFloat() < AEConfig.instance.meteoriteSpawnChance ) + if( r.nextFloat() < AEConfig.instance.meteoriteSpawnChance ) { - int x = r.nextInt( 16 ) + (chunkX << 4); - int z = r.nextInt( 16 ) + (chunkZ << 4); + int x = r.nextInt( 16 ) + ( chunkX << 4 ); + int z = r.nextInt( 16 ) + ( chunkZ << 4 ); int depth = 180 + r.nextInt( 20 ); TickHandler.INSTANCE.addCallable( w, new MeteoriteSpawn( x, depth, z, w ) ); @@ -60,6 +61,49 @@ final public class MeteoriteWorldGen implements IWorldGenerator WorldSettings.getInstance().getCompass().updateArea( w, chunkX, chunkZ ); } + private boolean tryMeteorite( World w, int depth, int x, int z ) + { + for( int tries = 0; tries < 20; tries++ ) + { + MeteoritePlacer mp = new MeteoritePlacer(); + + if( mp.spawnMeteorite( new ChunkOnly( w, x >> 4, z >> 4 ), x, depth, z ) ) + { + int px = x >> 4; + int pz = z >> 4; + + for( int cx = px - 6; cx < px + 6; cx++ ) + for( int cz = pz - 6; cz < pz + 6; cz++ ) + { + if( w.getChunkProvider().chunkExists( cx, cz ) ) + { + if( px == cx && pz == cz ) + continue; + + if( WorldSettings.getInstance().hasGenerated( w.provider.dimensionId, cx, cz ) ) + { + MeteoritePlacer mp2 = new MeteoritePlacer(); + mp2.spawnMeteorite( new ChunkOnly( w, cx, cz ), mp.getSettings() ); + } + } + } + + return true; + } + + depth -= 15; + if( depth < 40 ) + return false; + } + + return false; + } + + private Collection getNearByMeteorites( World w, int chunkX, int chunkZ ) + { + return WorldSettings.getInstance().getNearByMeteorites( w.provider.dimensionId, chunkX, chunkZ ); + } + class MeteoriteSpawn implements Callable { @@ -68,7 +112,8 @@ final public class MeteoriteWorldGen implements IWorldGenerator final World w; final int depth; - public MeteoriteSpawn(int x, int depth, int z, World w) { + public MeteoriteSpawn( int x, int depth, int z, World w ) + { this.x = x; this.z = z; this.w = w; @@ -84,7 +129,7 @@ final public class MeteoriteWorldGen implements IWorldGenerator double minSqDist = Double.MAX_VALUE; // near by meteorites! - for (NBTTagCompound data : MeteoriteWorldGen.this.getNearByMeteorites( this.w, chunkX, chunkZ )) + for( NBTTagCompound data : MeteoriteWorldGen.this.getNearByMeteorites( this.w, chunkX, chunkZ ) ) { MeteoritePlacer mp = new MeteoritePlacer(); mp.spawnMeteorite( new ChunkOnly( this.w, chunkX, chunkZ ), data ); @@ -92,9 +137,9 @@ final public class MeteoriteWorldGen implements IWorldGenerator minSqDist = Math.min( minSqDist, mp.getSqDistance( this.x, this.z ) ); } - boolean isCluster = (minSqDist < 30 * 30) && Platform.getRandomFloat() < AEConfig.instance.meteoriteClusterChance; + boolean isCluster = ( minSqDist < 30 * 30 ) && Platform.getRandomFloat() < AEConfig.instance.meteoriteClusterChance; - if ( minSqDist > AEConfig.instance.minMeteoriteDistanceSq || isCluster ) + if( minSqDist > AEConfig.instance.minMeteoriteDistanceSq || isCluster ) MeteoriteWorldGen.this.tryMeteorite( this.w, this.depth, this.x, this.z ); WorldSettings.getInstance().setGenerated( this.w.provider.dimensionId, chunkX, chunkZ ); @@ -103,48 +148,4 @@ final public class MeteoriteWorldGen implements IWorldGenerator return null; } } - - private boolean tryMeteorite(World w, int depth, int x, int z) - { - for (int tries = 0; tries < 20; tries++) - { - MeteoritePlacer mp = new MeteoritePlacer(); - - if ( mp.spawnMeteorite( new ChunkOnly( w, x >> 4, z >> 4 ), x, depth, z ) ) - { - int px = x >> 4; - int pz = z >> 4; - - for (int cx = px - 6; cx < px + 6; cx++) - for (int cz = pz - 6; cz < pz + 6; cz++) - { - if ( w.getChunkProvider().chunkExists( cx, cz ) ) - { - if ( px == cx && pz == cz ) - continue; - - if ( WorldSettings.getInstance().hasGenerated( w.provider.dimensionId, cx, cz ) ) - { - MeteoritePlacer mp2 = new MeteoritePlacer(); - mp2.spawnMeteorite( new ChunkOnly( w, cx, cz ), mp.getSettings() ); - } - } - } - - return true; - } - - depth -= 15; - if ( depth < 40 ) - return false; - } - - return false; - } - - private Collection getNearByMeteorites(World w, int chunkX, int chunkZ) - { - return WorldSettings.getInstance().getNearByMeteorites( w.provider.dimensionId, chunkX, chunkZ ); - } - } diff --git a/src/main/java/appeng/worldgen/QuartzWorldGen.java b/src/main/java/appeng/worldgen/QuartzWorldGen.java index 399e3ea20..4dd572975 100644 --- a/src/main/java/appeng/worldgen/QuartzWorldGen.java +++ b/src/main/java/appeng/worldgen/QuartzWorldGen.java @@ -60,25 +60,25 @@ final public class QuartzWorldGen implements IWorldGenerator { int seaLevel = w.provider.getAverageGroundLevel() + 1; - if ( seaLevel < 20 ) + if( seaLevel < 20 ) { int x = ( chunkX << 4 ) + 8; int z = ( chunkZ << 4 ) + 8; seaLevel = w.getHeightValue( x, z ); } - if ( this.oreNormal == null || this.oreCharged == null ) + if( this.oreNormal == null || this.oreCharged == null ) return; double oreDepthMultiplier = AEConfig.instance.quartzOresClusterAmount * seaLevel / 64; int scale = (int) Math.round( r.nextGaussian() * Math.sqrt( oreDepthMultiplier ) + oreDepthMultiplier ); - for ( int x = 0; x < ( r.nextBoolean() ? scale * 2 : scale ) / 2; ++x ) + for( int x = 0; x < ( r.nextBoolean() ? scale * 2 : scale ) / 2; ++x ) { boolean isCharged = r.nextFloat() > AEConfig.instance.spawnChargedChance; WorldGenMinable whichOre = isCharged ? this.oreCharged : this.oreNormal; - if ( WorldGenRegistry.INSTANCE.isWorldGenEnabled( isCharged ? WorldGenType.ChargedCertusQuartz : WorldGenType.CertusQuartz, w ) ) + if( WorldGenRegistry.INSTANCE.isWorldGenEnabled( isCharged ? WorldGenType.ChargedCertusQuartz : WorldGenType.CertusQuartz, w ) ) { int cx = chunkX * 16 + r.nextInt( 22 ); int cy = r.nextInt( 40 * seaLevel / 64 ) + r.nextInt( 22 * seaLevel / 64 ) + 12 * seaLevel / 64; diff --git a/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java b/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java index f2484f192..a8cf829d0 100644 --- a/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java +++ b/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java @@ -50,7 +50,7 @@ public class ChunkOnly extends StandardWorld @Override public int getBlockMetadata( int x, int y, int z ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) return this.target.getBlockMetadata( x & 0xF, y, z & 0xF ); return 0; } @@ -58,7 +58,7 @@ public class ChunkOnly extends StandardWorld @Override public Block getBlock( int x, int y, int z ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) return this.target.getBlock( x & 0xF, y, z & 0xF ); return Platform.AIR; } @@ -66,7 +66,7 @@ public class ChunkOnly extends StandardWorld @Override public void setBlock( int x, int y, int z, Block blk ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) { this.verticalBits |= 1 << ( y >> 4 ); this.w.setBlock( x, y, z, blk, 0, 1 ); @@ -76,7 +76,7 @@ public class ChunkOnly extends StandardWorld @Override public void setBlock( int x, int y, int z, Block blk, int metadata, int flags ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) { this.verticalBits |= 1 << ( y >> 4 ); this.w.setBlock( x, y, z, blk, metadata, flags & ( ~2 ) ); @@ -86,7 +86,7 @@ public class ChunkOnly extends StandardWorld @Override public void done() { - if ( this.verticalBits != 0 ) + if( this.verticalBits != 0 ) Platform.sendChunk( this.target, this.verticalBits ); } diff --git a/src/main/java/appeng/worldgen/meteorite/Fallout.java b/src/main/java/appeng/worldgen/meteorite/Fallout.java index de5c5e263..008e143be 100644 --- a/src/main/java/appeng/worldgen/meteorite/Fallout.java +++ b/src/main/java/appeng/worldgen/meteorite/Fallout.java @@ -27,11 +27,11 @@ public class Fallout public void getRandomFall( IMeteoriteWorld w, int x, int y, int z ) { double a = Math.random(); - if ( a > 0.9 ) + if( a > 0.9 ) this.putter.put( w, x, y, z, Blocks.stone ); - else if ( a > 0.8 ) + else if( a > 0.8 ) this.putter.put( w, x, y, z, Blocks.cobblestone ); - else if ( a > 0.7 ) + else if( a > 0.7 ) this.putter.put( w, x, y, z, Blocks.dirt ); else this.putter.put( w, x, y, z, Blocks.gravel ); @@ -40,20 +40,20 @@ public class Fallout public void getRandomInset( IMeteoriteWorld w, int x, int y, int z ) { double a = Math.random(); - if ( a > 0.9 ) + if( a > 0.9 ) this.putter.put( w, x, y, z, Blocks.cobblestone ); - else if ( a > 0.8 ) + else if( a > 0.8 ) this.putter.put( w, x, y, z, Blocks.stone ); - else if ( a > 0.7 ) + else if( a > 0.7 ) this.putter.put( w, x, y, z, Blocks.grass ); - else if ( a > 0.6 ) + else if( a > 0.6 ) { - for ( Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) + for( Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) { this.putter.put( w, x, y, z, skyStoneBlock ); } } - else if ( a > 0.5 ) + else if( a > 0.5 ) this.putter.put( w, x, y, z, Blocks.gravel ); else this.putter.put( w, x, y, z, Platform.AIR ); diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java b/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java index 1c0ac84c3..219201084 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java @@ -29,7 +29,7 @@ public class FalloutCopy extends Fallout public void getRandomFall( IMeteoriteWorld w, int x, int y, int z ) { double a = Math.random(); - if ( a > SPECIFIED_BLOCK_THRESHOLD ) + if( a > SPECIFIED_BLOCK_THRESHOLD ) { this.putter.put( w, x, y, z, this.block, this.meta ); } @@ -48,11 +48,11 @@ public class FalloutCopy extends Fallout public void getRandomInset( IMeteoriteWorld w, int x, int y, int z ) { double a = Math.random(); - if ( a > SPECIFIED_BLOCK_THRESHOLD ) + if( a > SPECIFIED_BLOCK_THRESHOLD ) { this.putter.put( w, x, y, z, this.block, this.meta ); } - else if ( a > AIR_BLOCK_THRESHOLD ) + else if( a > AIR_BLOCK_THRESHOLD ) { this.putter.put( w, x, y, z, Platform.AIR ); } diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutSand.java b/src/main/java/appeng/worldgen/meteorite/FalloutSand.java index 869dc9a08..de677d1a6 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutSand.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutSand.java @@ -26,7 +26,7 @@ public class FalloutSand extends FalloutCopy @Override public void getOther( IMeteoriteWorld w, int x, int y, int z, double a ) { - if ( a > GLASS_THRESHOLD ) + if( a > GLASS_THRESHOLD ) this.putter.put( w, x, y, z, Blocks.glass ); } } \ No newline at end of file diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java b/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java index 173b5f801..a6e853022 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java @@ -27,11 +27,11 @@ public class FalloutSnow extends FalloutCopy @Override public void getOther( IMeteoriteWorld w, int x, int y, int z, double a ) { - if ( a > SNOW_THRESHOLD ) + if( a > SNOW_THRESHOLD ) { this.putter.put( w, x, y, z, Blocks.snow ); } - else if ( a > ICE_THRESHOLD ) + else if( a > ICE_THRESHOLD ) { this.putter.put( w, x, y, z, Blocks.ice ); } diff --git a/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java b/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java index 6bb4a726d..692e64046 100644 --- a/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java +++ b/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java @@ -11,7 +11,7 @@ public class MeteoriteBlockPutter { Block original = w.getBlock( i, j, k ); - if ( original == Blocks.bedrock || original == blk ) + if( original == Blocks.bedrock || original == blk ) return false; w.setBlock( i, j, k, blk ); @@ -20,7 +20,7 @@ public class MeteoriteBlockPutter public void put( IMeteoriteWorld w, int i, int j, int k, Block blk, int meta ) { - if ( w.getBlock( i, j, k ) == Blocks.bedrock ) + if( w.getBlock( i, j, k ) == Blocks.bedrock ) { return; } diff --git a/src/main/java/appeng/worldgen/meteorite/StandardWorld.java b/src/main/java/appeng/worldgen/meteorite/StandardWorld.java index 6656c4efc..8337bc013 100644 --- a/src/main/java/appeng/worldgen/meteorite/StandardWorld.java +++ b/src/main/java/appeng/worldgen/meteorite/StandardWorld.java @@ -51,7 +51,7 @@ public class StandardWorld implements IMeteoriteWorld @Override public int getBlockMetadata( int x, int y, int z ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) return this.w.getBlockMetadata( x, y, z ); return 0; } @@ -59,7 +59,7 @@ public class StandardWorld implements IMeteoriteWorld @Override public Block getBlock( int x, int y, int z ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) return this.w.getBlock( x, y, z ); return Platform.AIR; } @@ -67,7 +67,7 @@ public class StandardWorld implements IMeteoriteWorld @Override public boolean canBlockSeeTheSky( int x, int y, int z ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) return this.w.canBlockSeeTheSky( x, y, z ); return false; } @@ -75,7 +75,7 @@ public class StandardWorld implements IMeteoriteWorld @Override public TileEntity getTileEntity( int x, int y, int z ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) return this.w.getTileEntity( x, y, z ); return null; } @@ -89,14 +89,14 @@ public class StandardWorld implements IMeteoriteWorld @Override public void setBlock( int x, int y, int z, Block blk ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) this.w.setBlock( x, y, z, blk ); } @Override public void setBlock( int x, int y, int z, Block blk, int metadata, int flags ) { - if ( this.range( x, y, z ) ) + if( this.range( x, y, z ) ) this.w.setBlock( x, y, z, blk, metadata, flags ); }